<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

<link rel="shortcut icon" href="gfx/favicon.ico" />
<title>Fancy Gaming Simplifier</title>

<link type="text/css" href="css/redmond/jquery-ui-1.8.10.custom.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/jquery-1.5.2.min.js"></script>

<script type="text/javascript">
var cssArr = [
	"css/share.css",
	"css/demo_page.css",
	"css/demo_table.css",
	"css/demo_table_jui.css",
	"css/jquery.contextMenu.css",
	"css/jquery.tooltip.css"
];

for(var i=0;i<cssArr.length;i++)
{
	var path = cssArr[i]+'?_='+new Date().getTime();
	
	var fileref=document.createElement("link");
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("href", path);
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
}

var scriptsArr = [
	"scripts/jquery-ui.min.js",
	"scripts/jquery.tooltip.min.js",
	"scripts/jquery.utils.js",
	"scripts/jquery.contextMenu.js",
	"scripts/jquery.dataTables.min.js",
	"scripts/time.js",
	"scripts/notices.js",
	"browser_files/browser.js",
]

for(var i=0;i<scriptsArr.length;i++)
{
	var path = scriptsArr[i]+'?_='+new Date().getTime();
	
	var xhrObj = new XMLHttpRequest();
	xhrObj.open('GET', path, false);
	xhrObj.setRequestHeader("Content-Type", "text/plain");
	xhrObj.overrideMimeType('text/plain; charset=UTF-8');
	xhrObj.send('');
	
	var se = document.createElement('script');
	se.type = "text/javascript";
	se.text = xhrObj.responseText;
	document.getElementsByTagName('head')[0].appendChild(se);
	
	continue;

	var path = scriptsArr[i];
	
	var th = document.getElementsByTagName('head')[0];
	var s = document.createElement('script');
	s.setAttribute('type','text/javascript');
	s.setAttribute('src',path);
	th.appendChild(s);
}
</script>


<script type="text/javascript">
$.fn.dataTableExt.afnSortData['dom-text'] = function  ( oSettings, iColumn )
{
	var aData = [];
	$( 'td:eq('+iColumn+') span', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
		aData.push( $(this).text() );
	} );
	return aData;
}

jQuery.expr[':'].Contains = function(a,i,m){
     return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};

var loaded = 0;
var isScreenLocked = false;
var chatInterval = null;

var screenLockedData = []


function updateLoaded()
{
	if(loaded == 0)
	{
		if(bkP.isHTTPS)
		{
		//	$('body').children('br:first').after('<br /><br /><div id="httpsNotice" style="margin:0 auto;width:90%;text-align:center;" class="section"><span style="color: red;text-align: center; font-size: 2em;">'+bkP.getMsg('HTTPSmodeDetected')+'</span><br /><span style="color: red;text-align: center; font-size: 1.5em;">'+bkP.getMsg('HTTPSmodeNotice')+' <a href="http://www.howtonew.com/how-to-disable-https-in-facebook" target="_blank">http://www.howtonew.com/how-to-disable-https-in-facebook</a><br /></span><span>'+bkP.getMsg('HTTPSmodeMessageDisappear')+'</span></div>');
		}
	}
	loaded++;
	$( "#progressbar" ).progressbar('option', 'value', loaded*20);
	
	if(loaded == 5)
	{
		updateCount();
		$( "#dialog-loading" ).dialog("close");
		setInterval(function(){ updateTimeAgo($('.gameContent:visible').children('div:visible').attr('id')); }, 20000);
		checkIconsCountInGameSelector();
	}
}

function addDataToScreenLocked(callback, id, data)
{
	var el =
	{
		callback:	callback,
		id: 		id,
		data:		data
	}
	screenLockedData.push(el);
}

	
	function hiddenFeed(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var el1		= $('div#'+game+'BonusesPendingList');
		var el2 	= $('div#'+game+'ManualBonusesList');
		
		var text = '<strong>There was a problem collecting bonuses. This error could mean three things:<br /><br />- you have no stories for specific game<br />- you have hidden it in your newsfeed<br />- new layout changes on Facebook broke your ability to grab bonuses easily.<br /><br /><span style="color: green;font-size:1.1em;">In version 1.1.0.51 I have introduced a workaround for this problem which worked for all people so far. Read my guide here and follow steps:<br /><a href="https://www.facebook.com/note.php?note_id=250830888297032" style="color: red;font-size:1.2em;">How to use "Custom URL source for bonsues" in FGS v. 1.1.0.51</a></span></strong><br /><br /><br /><br />';
		
		if(el1.length > 0)
		{
			el1.prev().height(300).find('.submenuInfo').html(text);
		}
		else if(el2.length > 0)
		{
			el2.prev().height(300).find('.submenuInfo').html(text);			
		}
	}
	
	function SelectFavourites(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		
		ClearSelection(gameID);
		$('.favouritesTable', 'div#'+game+opt).find('input[name="neighArr[]"]:lt(25)').each(function() { $(this).click(); });
	}
	
	function ClearSelection(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		$('input[name="neighArr[]"]', 'div#'+game+opt).removeAttr('checked');
	}
	
	function SelectNonFavourites(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		
		ClearSelection(gameID);
		$('.neighborsTable', 'div#'+game+opt).find('input[name="neighArr[]"]:lt(25)').each(function() { $(this).click(); });
	}
	
	function listGifts(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		
		var el = $('.sendToGiftsList','div#'+game+opt);
		
		el.append('<h3 style="text-align: center">'+bkP.getMsg('MessageToAddToYourGift')+': <input type="text" name="messageToAdd" class="messageToAddToGift" /></h3><br /><br class="clear" style="clear:both"/>');
		
		for(var id in bkP.giftsArray[gameID])
		{
			var v = bkP.giftsArray[gameID][id];
			var img = (typeof v.image == 'undefined' ? 'http://fgs.googlecode.com/svn/branches/reqs/'+game+'/'+id+'.png' : v.image);
			
			el.append('<div class="selectGiftToSend" gameID="'+gameID+'" title="'+v.name+'" alt="'+v.name+'" giftID="'+id+'"><img  style="width: 32px; height: 32px;margin:2px auto;" src="'+img+'"><div style="font-size: 11px;">'+v.name+'</div></div>');
		}
		
		if(bkP.options.games[gameID].defaultGift == 0)
		{
			el.children('div:first').addClass('selected');
		}
		else
		{
			el.children('div[giftID="'+bkP.options.games[gameID].defaultGift+'"]').addClass('selected');
		}
		el.append('<br class="clear" style="clear:both"/>');
	}
	
	function SendGifts(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';

		var sendTo = [];
		
		$('input[name="neighArr[]"]:checked:visible','div#'+game+opt).each(function()
		{
			sendTo.push($(this).val());
		});
		
		if(sendTo.length == 0)
		{
			alert(bkP.getMsg('YouMustSelectAtLeastOnePerson'));
			return;
		}
		
		var messageToAddToGift = $('.sendToGiftsList > h3 > input.messageToAddToGift','div#'+game+opt).val();

		var gift 	 = $('.sendToGiftsList > div.selected','div#'+game+opt).attr('giftID');
		var giftName = $('.sendToGiftsList > div.selected','div#'+game+opt).attr('title');
		
		var params = {
			giftNameName: giftName,
			gift: gift,
			gameID:	gameID,
			sendTo: sendTo,
			messageToAdd: messageToAddToGift
		};
		
		$('div#'+game+opt, '#'+game+'Game').children().addClass('hide');
		$('div#'+game+'SendFreeGifts > .submenu', '#'+game+'Game').children('button:gt(0)').addClass('hide');
		
		$('div#'+game+opt, '#'+game+'Game').prepend('<div class="sendingGiftProgress"><h3 class="center"><img src="gfx/loading.gif"><br />'+bkP.getMsg('SendingGiftToNumberOfPeople', [giftName, sendTo.length])+'</h3></div>');
				
		bkP[game].Freegifts.Click(params);
		
		//bkP.frontierville.Freegifts.Click({gift:'care_package', gameID: '201278444497', sendTo: ['100001178615702']});
	}
	
	function freegiftSuccess(data, data2)
	{
		var gameID = data.gameID;
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		
		$('div#'+game+opt, '#'+game+'Game').children('.sendingGiftProgress').html('<h3 class="center"><img src="gfx/90px-check.png"><br /><img src="gfx/loading.gif"><br /> '+bkP.getMsg('Success')+'<br />'+bkP.getMsg('WaitingForUpdatedNeighborsList')+'</h3>');
		
		$(getGiftHistoryRow(gameID, data, data2)).prependTo('#'+game+'SendFreeGiftsHistoryList');
	}
	
	function freegiftError(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';	
		
		$('div#'+game+'SendFreeGifts > .submenu', '#'+game+'Game').children('button:gt(0)').removeClass('hide');
		$('div#'+game+opt, '#'+game+'Game').children().removeClass('hide');
		
		$('div#'+game+opt, '#'+game+'Game').children('.sendingGiftProgress').html('<h3 class="center"><img src="gfx/90px-cancel.png"><br />'+bkP.getMsg('ErrorWhileSendingGiftNotice')+'</h3>');
		
	}
	

	function getGiftHistoryRow(gameID, v, thankYou)
	{
		var game = bkP.gamesData[gameID].systemName;
		
		if(thankYou != '' && thankYou != 0)
		{
			var thankText = '<br /><br />'+bkP.getMsg('ThankYouGift');
		}
		else
		{
			var thankText = '';
		}	
		
		var giftImg = 'http://fgs.googlecode.com/svn/branches/reqs/'+game+'/'+v.gift+'.png';
		try
		{
			if(typeof bkP.giftsArray[gameID][v.gift].image != 'undefined')
			{
				giftImg = bkP.giftsArray[gameID][v.gift].image;
			}
		}
		catch (e) {	console.log(e); }
		
		
		
		return  '<div class="freegiftHistory updateTimeAgo" title="'+v.friend+'" alt="'+v.friend+'" time="'+v.time+'"><span class="timeAgo">'+format_time_ago(v.time)+'</span><br /><img  style="width: 32px; height: 32px;margin:2px auto;" src="'+giftImg+'"><div style="font-size: 11px;">'+v.friend+thankText+'</div></div>'
	}
	
	function checkIfBonusIsManual(gameID, typeText, text)
	{
		var ret = false;
		$(bkP.gamesData[gameID].filter.bonusesNewWindow).each(function(k,v)
		{
			var re = new RegExp(v, "i") ;
			
			if(re.test(typeText))
			{
				if(gameID == '10979261223' && text.indexOf('needs help in') != -1) // oddzielenie war od normalnych
					return true;
					
				
				ret = true;
				return false;
			}
		});
		
				
		return ret;
	}
	
	function checkIfRequestIsManual(gameID, typeText)
	{
		var ret = false;
		$(bkP.gamesData[gameID].filter.requestsNewWindow).each(function(k,v)
		{
			var re = new RegExp(v, "i") ;
			
			if(re.test(typeText))
			{
				ret = true;
				return false;
			}
		});
		
		return ret;
	}
	
	function getNewBonusRow(gameID, v)
	{
		var title = v.title;
		title = title.replace(/'/gi, '');

		var newUrl = v.url;
		
		var cleanText = replaceSpanInText(v.text);		
		
		return '<div onmousedown="onMouseDownTest(event)" id="'+v.id+'" gameID="'+gameID+'" title="'+cleanText+'" search-title= "'+title+'" time="'+v.time+'" url="'+newUrl+'" class="bonusItem showContext updateTimeAgo processBonusClick"><span class="timeAgo">'+format_time_ago(v.time)+'</span><span class="bonusError"></span><img NOsrc="'+v.image+'"><span class="title">'+v.title+'</span><span class="description hide">'+v.text+'</span><span class="deleteIcon" title="'+bkP.getMsg('ClearThisItem')+'"></span></div>';
	}
	
	function getNewRequestRow(gameID, v)
	{
		var game = bkP.gamesData[gameID].systemName;
		var title = v.title;
		title = title.replace(/'/gi, '');
		
		if(v.image.indexOf('http') != -1)
		{
			var url = v.image;
		}
		else
		{
			var url = 'http://fgs.googlecode.com/svn/branches/reqs/'+game+'/'+v.image+'.png';
		}
		
		var cleanText = replaceSpanInText(v.text);
		
		var postData = v.post;
		
		var addClass = '';
		
		if(postData.indexOf('{"') == 0)
		{
			postData = escape(postData);
			addClass = ' isMessageCenterGift';
		}

		
		return '<div id="'+v.id+'" gameID="'+gameID+'" search-title="'+title+'" title="'+cleanText+'" origTitle="'+v.title+'" time="'+v.time+'" postdata="'+postData+'" class="requestItem showContextRequests updateTimeAgo processRequestClick'+addClass+'"><span class="timeAgo">'+format_time_ago(v.time)+'</span><span class="bonusError"></span><img NOsrc="'+url+'" onError="processImageError(this)"><span class="title">'+v.title+'</span><span class="description hide">'+v.text+'</span></div>';
	}
	
	function getNewManualBonusRow(gameID, v)
	{
		var title = v.title;
		title = title.replace(/'/gi, '');
		
		return '<div id="'+v.id+'" gameID="'+gameID+'" search-title="'+title+'" title="'+title+'" time="'+v.time+'" url="'+v.url+'" class="manualItem showContextManual updateTimeAgo manualBonus processManualBonusClick"><span class="timeAgo">'+format_time_ago(v.time)+'</span><span class="bonusError"></span><img NOsrc="'+v.image+'"><span class="title">'+v.title+'</span><span class="description hide">'+v.text+'</span><span class="deleteIcon" title="'+bkP.getMsg('ClearThisItem')+'"></span></div>';
	}
	
	function getNewManualRequestRow(gameID, v)
	{
		var game = bkP.gamesData[gameID].systemName;
		var title = v.title;
		title = title.replace(/'/gi, '');
		
		if(v.image.indexOf('http') != -1)
		{
			var url = v.image;
		}
		else
		{
			var url = 'http://fgs.googlecode.com/svn/branches/reqs/'+game+'/'+v.image+'.png';
		}
		
		var postData = v.post;
		
		var addClass = '';
		
		if(postData.indexOf('{"') == 0)
		{
			postData = escape(postData);
			addClass = ' isMessageCenterGift';
		}
		
		return '<div id="'+v.id+'" gameID="'+gameID+'" search-title="'+title+'" title="'+title+'" origTitle="'+v.title+'" time="'+v.time+'" postdata="'+postData+'" class="manualItem updateTimeAgo manualRequest processManualRequestClick'+addClass+'"><span class="timeAgo">'+format_time_ago(v.time)+'</span><span class="bonusError"></span><img src="'+url+'" onError="processImageError(this)"><span class="title">'+v.title+'</span><span class="description hide">'+v.text+'</span></div>';
	}
	
	function processImageError(e)
	{
		var el = $(e);
		el.attr('src', 'icons/reqs/noimage.png');
	}
	
	function processManualBonusClick(el)
	{
		var gameID = el.attr('gameID');
		el.unbind('click');
		var URI = el.attr('url');
		el.remove();
		
		if(bkP.options.games[gameID].likeItemsRequiringAction)
		{
			bkP.likeBonus(el.attr('id'));
		}
		
		
		bkP.database.deleteItem('bonuses', gameID, el.attr('id'), 0);
		bkP.database.deleteItem('bonuses', gameID, el.attr('id'), 1);
		bkP.openURI(URI, true);
		
		
		updateCount(gameID);
	}
	
	function processManualRequestClick(el)
	{
	
		if(el.hasClass('isMessageCenterGift'))
		{
			alert('This is a message center gift. It doesn\'t support receiving in new tab.');
			return;
		}
		
		var gameID = el.attr('gameID');
		bkP.database.deleteItem('requests', gameID, el.attr('id'), 0);
		bkP.database.deleteItem('requests', gameID, el.attr('id'), 1);
		bkP.prepareLinkForGame('', el.attr('id'), el.attr('postData'), true);
		el.remove();
		updateCount(gameID);
	}
	
	function addNewBonus(data2)
	{
		var gameID = data2[0][1];
		var game = bkP.gamesData[gameID].systemName;
		
		if(isScreenLocked)
		{
			addDataToScreenLocked('addNewBonus', '', data2);
			return;
		}
		
		
		$('div#'+game+'BonusesPendingList', '#'+game+'Game').prev().height(85).find('.submenuInfo').html('');
		$('div#'+game+'ManualBonusesList', '#'+game+'Game').prev().height(85).find('.submenuInfo').html('');
		
		var html = '';
		var htmlManual = '';
			
		var ids = [];
		
		$(data2).each(function(ind,data)
		{
			var itID = parseInt(data[0]);
			
			if($.inArray(itID, ids) != -1 || $('#'+itID).length > 0)
				return;
			ids.push(itID);
			
			var v = {	id: data[0],	title: data[2],	text: data[3],	image: data[4],	url: data[5],	time: data[6]	}
			
			if(checkIfBonusIsManual(gameID, v.title, v.text))
			{
				htmlManual += getNewManualBonusRow(gameID, v);
			}
			else
			{		
				html += getNewBonusRow(gameID, v);
			}
		});

		$('div#'+game+'ManualBonusesList').prepend(htmlManual);
		$('div#'+game+'BonusesPendingList').prepend(html);

		processSwitchItemsDisplay();
		
		updateCount(gameID);
	}
	
	function processBonusClick(el)
	{
		if(el.hasClass('inProgress')) return;
		
		var gameID = el.attr('gameID');
		var game =  bkP.gamesData[gameID].systemName;
		
		el.disableContextMenu().unbind('click').addClass('inProgress');
		
		var img = el.find('img:last');
		
		if(img.attr('src'))
			var orig = img.attr('src');
		else if(img.attr('nosrc'))
		{
			var orig = img.attr('nosrc');
			img.removeAttr('nosrc');
		}
		else
			var orig = '';
		
		img.attr('orig-src', orig).attr('src', 'gfx/dl.gif').css({ width: '64px', height: '64px'});
		
		var obj = {
					id: el.attr('id'),
					url: el.attr('url'),
					game: game,
					type: 'bonus',
					title: el.attr('search-title')
				}
		
		
		if(game == 'farmville')
		{
			if(bkP.options.games[gameID].useRandomTimeoutOnBonuses)
			{
				bkP.xhrFarmQueue.push(obj);
				updateQueueCount();
				return true;
			}	
		}	
		
		bkP.xhrQueue.push(obj);
		updateQueueCount();
	}
	
	function processRequestClick(el)
	{
		if(el.hasClass('inProgress')) return;
		
		var gameID = el.attr('gameID');
		var game =  bkP.gamesData[gameID].systemName;
		
		el.disableContextMenu().unbind('click').addClass('inProgress');
		
		
		var img = el.find('img:last');
		
		if(img.attr('src'))
			var orig = img.attr('src');
		else if(img.attr('nosrc'))
		{
			var orig = img.attr('nosrc');
			img.removeAttr('nosrc');
		}
		else
			var orig = '';
			
		img.attr('orig-src', orig).attr('src', 'gfx/dl.gif').css({ width: '64px', height: '64px'});
		
		var obj = {
					id: el.attr('id'),
					post: el.attr('postData'),
					game: game,
					type: 'request',
					title: el.attr('search-title')
				}
		if(el.hasClass('isMessageCenterGift'))
		{
			obj.type = 'request_MC';
			obj.data = JSON.parse(unescape(obj.post));
			obj.gameID = gameID;
		}
		
		bkP.xhrQueue.push(obj);
		updateQueueCount();
	}
	
	function ReceiveVisibleBonuses(gameID)
	{
		ReceivePendingBonuses(gameID, true);
	}
	
	function ReceivePendingBonuses(gameID, onlyVisible)
	{
		if(onlyVisible != undefined)
			var addParam = ':visible';
		else
			var addParam = '';
		
		var game = bkP.gamesData[gameID].systemName;
		$('#'+game+'BonusesPendingList').children('div'+addParam).not('.inProgress').each(function(){
			processBonusClick($(this));
		});
	}
	
	function ReceiveVisibleGifts(gameID)
	{
		ReceivePendingRequests(gameID, true);
	}
	
	function ReceivePendingRequests(gameID, onlyVisible)
	{
		if(onlyVisible != undefined)
			var addParam = ':visible';
		else
			var addParam = '';
		
		var game = bkP.gamesData[gameID].systemName;
		$('#'+game+'RequestsPendingList').children('div'+addParam).not('.inProgress').each(function(){
			processRequestClick($(this));
		});
	}
	
	function bonusError(id, data)
	{
		var el = $('#'+id);
		el.find('.deleteIcon').remove();
		el.find('img:last').attr('src', 'gfx/90px-cancel.png');
		
		var error_text = (typeof(data.error_text) != 'undefined' && data.error_text != '' ? ' <img src="gfx/info.png" title="'+data.error_text+'" />' : '');
		
		el.attr('error', data.error);		
		el.find('.bonusError').html('('+data.error+' error)'+error_text);
		
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		updateQueueCount();
		
		if(isScreenLocked)
		{
			addDataToScreenLocked('bonusErrorFinish', id, data);
		}
		else
		{
			bonusErrorFinish(id, data);
		}
	}
	
	function bonusErrorFinish(id, data)
	{
		var el = $('#'+id);
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		if(data.error == 'connection' || data.error == 'other')
		{
			setTimeout(function() {
				el.enableContextMenu().removeClass('inProgress');
				el.find('img:last').attr('src', el.find('img:last').attr('orig-src'));
			}, 1000);
		}
		else
		{
			setTimeout(function()
			{
				el.addClass('withDesc');
				el.unbind('mousedown').unbind('contextmenu').unbind('mouseup').die().prependTo('#'+game+'FailedBonusesList');
				el.removeClass('hide').attr('time', data.time).find('.timeAgo').text(format_time_ago(data.time));
				el.find('.description').removeClass('hide');
				el.removeClass('processBonusClick');
				
				if(data.error == 'receiving')
				{
					el.addClass('processManualBonusClick').css('cursor', 'pointer !important').attr('title', bkP.getMsg('ClickToOpenThisItemInNewTab'));
				}
				
				updateCount(gameID);
				
				processSwitchItemsDisplay();
			}, 1000);
		}
	}
	
	function bonusSuccess(id, data)
	{
		var el = $('#'+id);
		el.find('.deleteIcon').remove();
		el.find('img:last').attr('src', 'gfx/90px-check.png');
		
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		updateQueueCount();
		
		if(isScreenLocked)
		{
			addDataToScreenLocked('bonusSuccessFinish', id, data);
		}
		else
		{
			bonusSuccessFinish(id, data);
		}
	}
	
	function bonusSuccessFinish(id, data)
	{
		var el = $('#'+id);
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
	
		setTimeout(function() 
		{
			el.addClass('withDesc');
			el.prependTo('#'+game+'BonusesHistoryList');
			el.removeClass('hide').removeClass('inProgress');

			if(data.image !== '')
			{
				el.find('img:last').attr('src', data.image);
			}
			else
			{
				el.find('img:last').attr('src', el.find('img:last').attr('orig-src'));
			}
			
			
			if(data.title != '')
			{
				el.find('.title').text(data.title);
			}
			
			
			var infoAdd = '';
			
			if(typeof(data.thanks) != 'undefined' && data.thanks != '')
			{
				infoAdd = JSON.stringify(data.thanks);
			}
			
			el.find('.bonusError').css('height', '23px').html(addLikeRow(false, infoAdd, false));
			
			if(typeof el.attr('isLiked') !== 'undefined')
			{
				updateLikeState('#'+id, 0);
			}
			
			if(typeof el.attr('isCommented') !== 'undefined')
			{
				updateCommentState('#'+id, 0);
			}
			
			el.find('.description').removeClass('hide');
			
			if(data.text != '')
			{
				el.attr('title', data.text);
				el.find('.description').removeClass('hide').html(data.text);
			}
			
			el.removeClass('processBonusClick');
			el.attr('time', data.time).find('.timeAgo').text(format_time_ago(data.time));
			updateCount(gameID);
			
			processSwitchItemsDisplay();
			
		}, 1000);
	}
	
	function addLikeRow(like, sendBack, comm, isRequest)
	{
		
		var sendBackHtml = '';

		if(sendBack != '' && sendBack != null && sendBack != '""')
		{
			var sendBackJson = JSON.parse(sendBack);
			
			if(typeof(sendBackJson.sent) == 'undefined')
			{
				var img3 = 'gfx/sendback.png';
				var enabled = 'true';
				var cursor = 'cursor: pointer';
				var className = 'sendBack';
				var desc = bkP.getMsg('ClickToSendThankYouGift');
			}
			else
			{
				var img3 = 'gfx/23check.png';
				var enabled = 'false';
				var cursor = '';
				var className = '';
				var desc = bkP.getMsg('ThankYouGiftAlreadySent');
			}
			sendBackHtml = '<img src="'+img3+'" class="'+className+'" isEnabled="'+enabled+'" title="'+desc+'" style="'+cursor+'"><span style="display: none">'+sendBack+'</span>';
		}
		
		if(typeof(isRequest) != 'undefined')
		{
			return '<div style="position: relative"><div style="position: absolute;left:48;">'+sendBackHtml+'</div></div>';
		}
		else
		{
			if(like == false || like == 0)
			{
				var img = 'gfx/like.png';
				var addClassLike = '';
			}
			else
			{
				var img = 'gfx/like-off.png';
				var addClassLike = ' disabledLike';
			}
			
			if(comm == false || comm == 0)
			{
				var img2 = 'gfx/comment.png';
				var addClassComm = '';
			}
			else
			{
				var img2 = 'gfx/comment-off.png';
				var addClassComm = ' disabledComment';
			}
		
			return '<div style="position: relative"><div style="position: absolute;left:0;"><img src="'+img+'" class="likeBonus'+addClassLike+'" title="'+bkP.getMsg('ClickToLike')+'" style="cursor: pointer"></div><div style="position: absolute;left:60;">'+sendBackHtml+'</div><div style="position: absolute;right:0;"><img src="'+img2+'" class="commentBonus'+addClassComm+'" title="'+bkP.getMsg('ClickToPostComment')+'" style="cursor: pointer"></div></div>';
		}
	}
	
	function requestError(id, data)
	{
		var el = $('#'+id);
		el.find('.deleteIcon').remove();
		el.find('img:last').attr('src', 'gfx/90px-cancel.png');
		
		var error_text = (typeof(data.error_text) != 'undefined'  && data.error_text != ''  ? ' <img src="gfx/info.png" title="'+data.error_text+'" />' : '');
		
		el.attr('error', data.error);		
		el.find('.bonusError').html('('+data.error+' error)'+error_text);
		
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		updateQueueCount();
		
		if(isScreenLocked)
		{
			addDataToScreenLocked('requestErrorFinish', id, data);
		}
		else
		{
			requestErrorFinish(id, data);
		}	
		
	}
	
	function requestErrorFinish(id, data)
	{
		var el = $('#'+id);
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		if(data.error == 'connection')
		{
			setTimeout(function() {
				el.enableContextMenu().removeClass('inProgress');
				el.find('img:last').attr('src', el.find('img:last').attr('orig-src'));
			}, 1000);
		}
		else
		{
			setTimeout(function() {
				el.addClass('withDesc').unbind('mousedown').unbind('contextmenu').unbind('mouseup').die().prependTo('#'+game+'FailedGiftsList');
				el.attr('time', data.time).find('.timeAgo').text(format_time_ago(data.time));
				el.find('.description').removeClass('hide');
				el.removeClass('processRequestClick');
				
				if(data.error == 'receiving')
				{
					el.addClass('processManualRequestClick').css('cursor', 'pointer !important').attr('title', bkP.getMsg('ClickToOpenThisItemInNewTab'));
				}				
				updateCount(gameID);
			}, 1000);
		}
	}
	
	function requestSuccess(id, data)
	{
		var el = $('#'+id);
		el.find('.deleteIcon').remove();
		el.find('img:last').attr('src', 'gfx/90px-check.png');
		
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		updateQueueCount();
		
		if(isScreenLocked)
		{
			addDataToScreenLocked('requestSuccessFinish', id, data);
		}
		else
		{
			requestSuccessFinish(id, data);
		}
		
	}
	
	
	function requestSuccessFinish(id, data)
	{
		var el = $('#'+id);
		var gameID = el.attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		
		setTimeout(function() {
			el.prependTo('#'+game+'RequestsHistoryList');
			el.addClass('withDesc').removeClass('inProgress');
			el.removeClass('processRequestClick');
			
			if(data.image !== '')
			{
				el.find('img:last').attr('src', data.image);
			}
			else
			{
				el.find('img:last').attr('src', el.find('img:last').attr('orig-src'));
			}
			
			
			if(data.title != '')
			{
				el.find('.title').text(data.title);
			}

			
			var infoAdd = '';
			
			if(typeof(data.thanks) != 'undefined' && data.thanks != '')
			{
				infoAdd = JSON.stringify(data.thanks);
			}
			
			el.find('.bonusError').css('height', '23px').html(addLikeRow(false, infoAdd, false, true));
			
			if(typeof el.attr('SendbackInProgress') !== 'undefined')
			{
				updateSendbackState('#'+id);
			}
			
			el.find('.title').next('span').removeClass('hide').text(data.text);
			el.attr('time', data.time).find('.timeAgo').text(format_time_ago(data.time));
			updateCount(gameID);
		}, 1000);
	}
	
	function ClearAllManualBonuses()
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					for(var gameID in bkP.gamesData)
					{
						var game = bkP.gamesData[gameID].systemName;
						
						if(bkP.options.games[gameID].enabled)
						{
							var delReqArr = [];
							var delBonArr = [];
							
							$('#'+game+'ManualBonusesList').children('div').each(function()
							{
								var elID = $(this).attr('id');
								if($(this).hasClass('manualRequest'))
								{
									var postData = $(this).attr('postData');
									
									if($(this).hasClass('isMessageCenterGift'))
									{
										var obj = {}
										obj.data = JSON.parse(unescape(postData));
										obj.gameID = gameID;
										obj.deleteItem = true;
										
										bkP[game].MessageCenter.Receive(obj);
									}
									else
									{
										bkP.emptyUnwantedGifts(postData);
									}
									
									delReqArr.push(elID);
								}
								else
								{
									delBonArr.push(elID);
								}
								
								$(this).remove();
							});
							
							while(delReqArr.length > 0)
							{
								var tmpArr = delReqArr.slice(0,500);
								
								var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
								bkP.database.deleteItemArray('requests', gameID, str, 0);
								
								delReqArr = delReqArr.slice(500);						
							}
							
							while(delBonArr.length > 0)
							{
								var tmpArr = delBonArr.slice(0,500);
								
								var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
								bkP.database.deleteItemArray('bonuses', gameID, str, 0);
								
								delBonArr = delBonArr.slice(500);						
							}
						}
					}
						
					processSwitchItemsDisplay();
					updateCount();					
					
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearManualBonuses(gameID, onlyVisible)
	{
		var game = bkP.gamesData[gameID].systemName;
		
		if(onlyVisible != undefined)
			var addParam = ':visible';
		else
			var addParam = '';
		
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var delReqArr = [];
					var delBonArr = [];

					$('#'+game+'ManualBonusesList').children('div'+addParam).each(function()
					{
						var elID = $(this).attr('id');
						if($(this).hasClass('manualRequest'))
						{
							var postData = $(this).attr('postData');
							
							if($(this).hasClass('isMessageCenterGift'))
							{
								var obj = {}
								obj.data = JSON.parse(unescape(postData));
								obj.gameID = gameID;
								obj.deleteItem = true;
								
								bkP[game].MessageCenter.Receive(obj);
							}
							else
							{
								bkP.emptyUnwantedGifts(postData);
							}
							
							delReqArr.push(elID);
						}
						else
						{
							delBonArr.push(elID);
						}
						
						$(this).remove();
					});
					
					while(delReqArr.length > 0)
					{
						var tmpArr = delReqArr.slice(0,500);
						
						var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
						bkP.database.deleteItemArray('requests', gameID, str, 0);
						
						delReqArr = delReqArr.slice(500);						
					}
					
					while(delBonArr.length > 0)
					{
						var tmpArr = delBonArr.slice(0,500);
						
						var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
						bkP.database.deleteItemArray('bonuses', gameID, str, 0);
						
						delBonArr = delBonArr.slice(500);						
					}
					
					processSwitchItemsDisplay();
					updateCount(gameID);
					
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearVisibleBonuses(gameID)
	{
		ClearPendingBonuses(gameID, true);
	}
	
	function ClearVisibleManualBonuses(gameID)
	{
		ClearManualBonuses(gameID, true);
	}
	
	function ClearPendingBonuses(gameID, onlyVisible)
	{
		if(onlyVisible != undefined)
			var addParam = ':visible';
		else
			var addParam = '';
			
			
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					var delArr = [];

					$('#'+game+'BonusesPendingList').children('div'+addParam).not('.inProgress').each(function()
					{
						delArr.push($(this).attr('id'));
						$(this).remove();
					});
					
					while(delArr.length > 0)
					{
						var tmpArr = delArr.slice(0,500);
						
						var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
						bkP.database.deleteItemArray('bonuses', gameID, str, 0);
						
						delArr = delArr.slice(500);						
					}
					updateCount(gameID);
					processSwitchItemsDisplay();
					
					
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearVisibleGifts(gameID)
	{
		ClearPendingRequests(gameID, true);
	}
	
	function ClearPendingRequests(gameID, onlyVisible)
	{
		if(onlyVisible != undefined)
			var addParam = ':visible';
		else
			var addParam = '';
			
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
		
					var delArr = [];
					
					$('#'+game+'RequestsPendingList').children('div'+addParam).not('.inProgress').each(function()
					{
						var el = $(this);
						
						var postData = el.attr('postData');
						delArr.push(el.attr('id'));
						try
						{
							if(el.hasClass('isMessageCenterGift'))
							{
								var obj = {}
								obj.data = JSON.parse(unescape(postData));
								obj.gameID = gameID;
								obj.deleteItem = true;
								
								bkP[game].MessageCenter.Receive(obj);
							}
							else
							{
								bkP.emptyUnwantedGifts(postData);
							}
						} catch(e) {}
						el.remove();
					});
					
					while(delArr.length > 0)
					{
						var tmpArr = delArr.slice(0,500);
						
						var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
						bkP.database.deleteItemArray('requests', gameID, str, 0);
						
						delArr = delArr.slice(500);						
					}
					
					processSwitchItemsDisplay();
					updateCount(gameID);

					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearCollectedBonuses(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'BonusesHistoryList').html('<br style="clear:both" />');
					updateCount(gameID);
					bkP.database.clearTable('bonuses', gameID, 1);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearPendingBonusesOtherError(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('Clear')+' "Other errors"');
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					
					var delArr = [];
					
					
					$('#'+game+'BonusesPendingList').children('div').not('.inProgress').each(function()
					{
					
						if($(this).attr('error') == 'other')
						{
							delArr.push($(this).attr('id'));
							$(this).remove();
						}
					});
					
					while(delArr.length > 0)
					{
						var tmpArr = delArr.slice(0,500);
						
						var str = ' where id = "'+tmpArr.join('" or id = "')+'" ';
						bkP.database.deleteItemArray('bonuses', gameID, str, 0);
						
						delArr = delArr.slice(500);						
					}
					updateCount(gameID);
					processSwitchItemsDisplay()
					
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearCollectedBonusesLimitError(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('Clear')+' "Limit errors"');
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'FailedBonusesList').children('div').each(function(){
						if($(this).attr('error') == 'limit')
						{
							$(this).remove();
						}
					});
					//('<br style="clear:both" />');
					bkP.database.clearLimitErrors(gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearAllFailedBonuses(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'FailedBonusesList').children('div').each(function(){
						$(this).remove();
					});
					bkP.database.clearFailedBonuses(gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearAllFailedRequests(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'FailedGiftsList').children('div').each(function(){
						$(this).remove();
					});
					//('<br style="clear:both" />');
					bkP.database.clearFailedGifts(gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearCollectedBonusesReceivingError(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('Clear')+' "Receiving errors"');
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'FailedBonusesList').children('div').each(function()
					{
						if($(this).attr('error') == 'receiving')
						{
							$(this).remove();
						}
					});
					//('<br style="clear:both" />');
					bkP.database.clearReceivingErrors(gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearCollectedRequestsReceivingError(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('Clear')+' "Receiving errors"');
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'FailedGiftsList').children('div').each(function(){
						if($(this).attr('error') == 'receiving')
						{
							$(this).remove();
						}
					});
					//('<br style="clear:both" />');
					bkP.database.clearRequestReceivingErrors(gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearCollectedRequestsLimitError(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('Clear')+' "Limit errors"');
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'FailedGiftsList').children('div').each(function(){
						if($(this).attr('error' ) == 'limit')
						{
							$(this).remove();
						}
					});
					//('<br style="clear:both" />');
					bkP.database.clearRequestLimitErrors(gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	
	function ClearCollectedRequests(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'RequestsHistoryList').html('<br style="clear:both" />');
					updateCount(gameID);
					bkP.database.clearTable('requests', gameID, 1);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function ClearSentFreeGifts(gameID)
	{
		$('#dialog-confirm').dialog({
			open: function()
			{
				$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
				$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
			},
			buttons:
			{
				Clear: function()
				{
					var game = bkP.gamesData[gameID].systemName;
					$('#'+game+'SendFreeGiftsHistoryList').html('<br style="clear:both" />');
					bkP.database.clearTable('freegifts', gameID);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
		}});
		
		$('#dialog-confirm').dialog('open');
	}
	
	function addNewRequest(data2)
	{
		var htmls = {};
		var htmlsManual = {};
		
		if(isScreenLocked)
		{
			addDataToScreenLocked('addNewRequest', '', data2);
			return;
		}
		
		var ids = [];
		
		$(data2).each(function(ind,data)
		{
			var itID = parseInt(data[0]);
			
			if($.inArray(itID, ids) != -1 || $('#'+itID).length > 0)
				return;
			
			ids.push(itID);
			
			var v = {	id: data[0],	title: data[2],	text: data[3],	image: data[4], post: data[5],	time: data[6]	}
			
			var gameID = data[1];
			
			if(typeof(htmls[gameID]) == 'undefined')
			{
				htmls[gameID] = '';
				htmlsManual[gameID] = '';
			}			
			
			if(checkIfRequestIsManual(gameID, v.text))
			{
				htmlsManual[gameID] += getNewManualRequestRow(gameID, v);
			}
			else
			{		
				htmls[gameID] += getNewRequestRow(gameID, v);
			}
		});

		
		for(var tmp in htmls)
		{
			var game = bkP.gamesData[tmp].systemName;
			$('div#'+game+'ManualBonusesList').prepend(htmlsManual[tmp]);
			$('div#'+game+'RequestsPendingList').prepend(htmls[tmp]);
		}
		
		
		processSwitchItemsDisplay();
		
		updateCount();
	}


	function calcage(secs, num1, num2)
	{
		s = ((Math.floor(secs/num1))%num2).toString();
		if (s.length < 2)
			s = "0" + s;
		return s;
	}

	
	function updateCount(gameID)
	{
		var processList = {};

		if(typeof(gameID) == 'undefined')
		{
			for(var idd in bkP.gamesData)
			{
				if(bkP.options.games[idd].enabled)
				{
					processList[idd] = true;
				}
			}
		}
		else
		{
			processList[gameID] = true;
		}
		
		for(var idd2 in processList)
		{		
			var game = bkP.gamesData[idd2].systemName;
			
			var totCount = 0;
			
			var bCount = $('#'+game+'BonusesPendingList > div').length;
			var rCount = $('#'+game+'RequestsPendingList > div').length;
			var mCount = $('#'+game+'ManualBonusesList > div').length;
			
			totCount += bCount;
			totCount += rCount;
			totCount += mCount;
			
			
			$('a[href="#'+game+'BonusesPending"]').find('span').text(bCount);
			$('a[href="#'+game+'RequestsPending"]').find('span').text(rCount);
			$('a[href="#'+game+'ManualBonuses"]').find('span').text(mCount);
			$('label[for="'+game+'Selected"]').find('.badgeDiv').removeClass('hide').children('span').text(totCount);
		}
	}


	function getBonusHistoryRow(v)
	{
		if(!v.error_text)
		{
			var errorText = '';
		}
		else
		{
			var errorText = v.error_text;
		}

		var error_text = (errorText != '' ? ' <img src="gfx/info.png" title="'+errorText+'" />' : '');		
		
		var err = (v.error == error_text ? addLikeRow(v.like_bonus, v.resend_gift, v.comment_bonus) : '('+v.error+' error)'+error_text)
		
		if(v.image == 'undefined' && error_text == '')
		{
			var showImage = 'gfx/90px-check.png';
		}
		else
		{
			var showImage = v.image;
		}
		
		var addClass = '';
		
		
		if(v.error == 'receiving')
		{
			addClass = ' processManualBonusClick ';
		}
		else if(v.error == '')
		{
			addClass = ' noErrorClass ';
		}
		
		var cleanText = replaceSpanInText(v.text);
		
		return '<div id="'+v.id+'" error='+v.error+' gameID="'+v.gameID+'" time="'+v.time+'" url="'+v.url+'" title="'+cleanText+'" class="bonusItem withDesc disabled updateTimeAgo '+addClass+'"><span class="timeAgo">'+format_time_ago(v.time)+'</span><span class="bonusError">'+err+'</span><img src="'+showImage+'"><span class="title">'+v.title+'</span><span class="description">'+v.text+'</span></div>';
	}
	
	function replaceSpanInText(t)
	{
		var pos0 = t.indexOf('><br');
		if(pos0 == -1)
			return t;
		var pos1 = t.indexOf('>', pos0+1)+1;
		
		t = t.slice(pos1);
		
		return t;
	}
	
	function getRequestHistoryRow(v)
	{
		if(!v.error_text)
		{
			var errorText = '';
		}
		else
		{
			var errorText = v.error_text;
		}
		
		var error_text = (errorText != '' ? ' <img src="gfx/info.png" title="'+errorText+'" />' : '');
		
		
		var err = (v.error == error_text ? addLikeRow(false, v.resend_gift, false, true) : '('+v.error+' error)'+error_text);
		
		var addClass = '';
		if(v.error == 'receiving')
		{
			addClass = ' processManualRequestClick ';
		}
		else if(v.error == '')
		{
			addClass = ' noErrorClass ';
		}
		
		var cleanText = replaceSpanInText(v.text);
		
		var postData = v.post;
		
		var addClass2 = '';
		
		if(postData.indexOf('{"') == 0)
		{
			postData = escape(postData);
			addClass2 = ' isMessageCenterGift';
		}
		
		return '<div id="'+v.id+'" error="'+v.error+'" gameID="'+v.gameID+'" title="'+cleanText+'" time="'+v.time+'" postData="'+postData+'" class="withDesc requestItem disabled updateTimeAgo'+addClass + addClass2+'"><span class="timeAgo">'+format_time_ago(v.time)+'</span><span class="bonusError">'+err+'</span><img src="'+v.image+'" onError="processImageError(this)"><span class="title">'+v.title+'</span><span class="description">'+v.text+'</span></div>';
	}
	
	function friendsLoaded(gameID, status)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'NeighborsSearchList';
		
		if(!status)
			var html = '<h3 class="center">'+bkP.getMsg('ThereWasAProblemTryAgainLater')+'</h3>';
		else
		{
			if(status.users.length == 0)
				var html = '<h3 class="center">'+bkP.getMsg('NoPeopleLookingForNeighborsInThisGame')+'</h3>';
			else
			{
				var html = '<h3 class="center">'+bkP.getMsg('ThesePeopleAreLookingForNeighbors')+':</h3>';
				$(status.users).each(function(k,v)
				{
					html+='<div class="friendsList"><a href="https://www.facebook.com/addfriend.php?id='+v+'&fromFGS='+escape(bkP.gamesData[gameID].name)+'" class="friendLink" target="_blank">'+v+'</a></div>';
				});
				html+= '<br style="clear: both" /><br /><div class="pagination">';
				
				var page = status.page;
				var totalPage = status.total;
				
				if(page > 1)
				{
					html += '<a class="friendsPageLink paginxtext" style="cursor: pointer;" gameID="'+gameID+'" page="'+1+'">First</a> ';	
					html += '<a class="friendsPageLink paginxtext" style="cursor: pointer;" gameID="'+gameID+'" page="'+(page-1)+'">Previous</a> ';		
				}
				
				for(var i=(page-3 > 0 ? page-3 : 1);i<page;i++)
				{
					html += '<a class="friendsPageLink paginx" style="cursor: pointer;" gameID="'+gameID+'" page="'+(i)+'">'+i+'</a> ';
				}
				
				html += '<a class="paginxsel">'+i+'</a> ';
				
				for(var i = page+1; i < totalPage && i < (page+4); i++)
				{
					html += '<a class="friendsPageLink paginx" style="cursor: pointer;" gameID="'+gameID+'" page="'+(i)+'">'+i+'</a> ';
				}
				
				if(totalPage > page)
				{
					html += '<a class="friendsPageLink paginxtext" style="cursor: pointer;" gameID="'+gameID+'" page="'+(page+1)+'">Next</a> ';	
					html += '<a class="friendsPageLink paginxtext" style="cursor: pointer;" gameID="'+gameID+'" page="'+totalPage+'">Last</a> ';		
				}
				html += '</div>';
			}
		}
		$('div#'+game+opt, '#'+game+'Game').find('.searchForPeopleList').html(html);
	}
	
	function friendsPaginate(el)
	{
		CheckIfNeighborsAvailable(el.attr('gameID'), el.attr('page'));
	}
	
	function CheckIfNeighborsAvailable(gameID, page)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'NeighborsSearchList';
		
		if(!page)
		{
			var page = 1;
		}
		
		if(!$(".gameListOnNeighborsSearch[gameID='"+gameID+"']").is(':checked'))
		{
			alert(bkP.getMsg('MustCheckListMeOnNeighborsSearchBeforeSearch'));
			return;
		}
		
		$('div#'+game+opt, '#'+game+'Game').html('<h2 class="center">Found people:</h2> <div class="searchForPeopleList"><h3 class="center"><img src="gfx/loading.gif"><br />Looking for people who are not already your neighbors... Please wait...</h3></div>');
		
		bkP.searchForNeighbors.Step1(gameID, page);
	}
	
	function neighborsLoaded(users, gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		
		$('.sendingGiftProgress','div#'+game+opt).remove();
		
		if(!users)
		{
			var html = '<h3 class="center">'+bkP.getMsg('ThereWasAProblemTryAgainLater')+'</h3>';
			$('.sendToNeighboursList','div#'+game+opt).html(html);
		}
		else
		{
			var favArr = [], norArr = [];
			var favObj = {}, norObj = {}
			var favCnt = norCnt = 0;
			
			$(users).each(function(k,val)
			{
				for(var i in val)
				{
					var id = i;
				}
				var v = val[id];
				
				if($.inArray(id, bkP.options.games[gameID].favourites) != -1)
				{
					favObj[id] = favCnt;
					favCnt++;
					favArr.push([
						'<img src="icons/favourite.png" gameID="'+gameID+'" neighID="'+id+'" class="toggleFavourite">',
						'<a href="https://www.facebook.com/profile.php?id='+id+'" target="_blank">'+v.name+'</a>',
						'<span class="hide">0</span>'+bkP.getMsg('Never'),
						'<span class="hide">0</span>'+bkP.getMsg('Never'),
						'<span class="hide">0</span>'+bkP.getMsg('Never'),
						'<span class="hide">0</span>0',
						'<span class="hide">0</span>0',
						'<span class="hide">0</span>0',
						'<input type="checkbox" value="'+id+'" gameID="'+gameID+'" neighID="'+id+'" class="selectNeighborToSend" name="neighArr[]">'
					]);
				}
				else
				{
					norObj[id] = norCnt;
					norCnt++;
					
					norArr.push([
						'<img src="icons/favourite-bw.png" gameID="'+gameID+'" neighID="'+id+'" class="toggleFavourite">', 
						'<a href="https://www.facebook.com/profile.php?id='+id+'" target="_blank">'+v.name+'</a>',
						'<span class="hide">0</span>'+bkP.getMsg('Never'),
						'<span class="hide">0</span>'+bkP.getMsg('Never'),
						'<span class="hide">0</span>'+bkP.getMsg('Never'),
						'<span class="hide">0</span>0',
						'<span class="hide">0</span>0',
						'<span class="hide">0</span>0',
						'<input type="checkbox" value="'+id+'" gameID="'+gameID+'" neighID="'+id+'" class="selectNeighborToSend" name="neighArr[]">'
					]);
				}	
			});
			
			var data = 
			{
				nor: norObj,
				fav: favObj,
				norArr: norArr,
				favArr: favArr
			}
			
			loadNeighborsStats(gameID, data);
		}
		
		
	}
	
	function LoadNeighborsList(gameID)
	{
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
		
		$('div#'+game+opt, '#'+game+'Game').html('<h2 class="center hide">'+bkP.getMsg('FavouriteNeighbors')+'</h2> <div class="sendToFavouritesList hide"></div> <h2 class="center hide">'+bkP.getMsg('AvailableGifts')+'</h2> <div class="hide sendToGiftsList"></div> <h2 class="center">'+bkP.getMsg('Neighbors')+'</h2> <div class="sendToNeighboursList"><h3 class="center"><img src="gfx/loading.gif"><br />'+bkP.getMsg('LoadingNeighborsPleaseWait')+'</h3></div>');
		
		listGifts(gameID);
		
		setTimeout(function(){ bkP.ListNeighbours(gameID) }, 100);
	}


function startup()
{
	$('#currentVersion').text(bkP.currentVersion);
	prepareGameSelector();
	processGameListOnNeighborsSearch();
}


function prepareGameSelector()
{
	for(var gameID in bkP.gamesData)
	{
		addIconToGameSelector(gameID);
		addIconToOptionsMenu(gameID);
	}
	
	$('#gameOptionsTab').append('<br style="clear: both" />');
	
	
	// dodaj chat i opcje
	$('<input type="radio" class="gameSelectorInput" name="gameSelectorInput" id="chatSelected" /><label gameName="Chat" for="chatSelected"><img src="icons/menu/chat.png"></label>').appendTo('#gameSelector');
	
	$('<input type="radio" class="gameSelectorInput" name="gameSelectorInput" id="contactSelected" /><label gameName="Contact" for="contactSelected"><img src="icons/menu/48contact.png"></label>').appendTo('#gameSelector');
	
	$('<input type="radio" class="gameSelectorInput" name="gameSelectorInput" id="optionsSelected" /><label gameName="Options" for="optionsSelected"><img src="icons/menu/options.png"></label>').appendTo('#gameSelector');
	
	$('#gameSelector').children('label').contextMenu({
			menu: 'myMenuGameIcon'
		}, function(action, el, pos)
		{
			if(action == 'goToGame')
			{
				var gameID = $(el).prev().attr('gameID');
				bkP.openURI(bkP.gamesData[gameID].link, false);
			}
	});
	
	$('#gameSelector').children('[gamename="Contact"], [gamename="Chat"], [gamename="Options"]').disableContextMenu();
	
	$('#gameSelector').children('label').tooltip({
		delay: 0,
		track: true,
		bodyHandler: function()
			{
				if($(this).is('[gamename="Contact"], [gamename="Chat"], [gamename="Options"]'))
					return '<h2>'+bkP.getMsg($(this).attr("gameName"))+'</h2>'; 
				else
					return '<h2>'+$(this).attr("gameName")+'</h2>'; 
			}, 
		positionLeft: true,
		showURL: false
	});
		
	$("#gameSelector").buttonset();
}

function addIconToOptionsMenu(gameID)
{
	var d =  bkP.gamesData[gameID];
	var e =  bkP.options.games[gameID];
	
	var addSpecOpt = '<br style="line-height: 19px;" />';
	
	if(gameID == '102452128776')
	{
		addSpecOpt = '<input type="checkbox" '+(e.useRandomTimeoutOnBonuses ? 'checked="checked"':'')+'  class="gameUseRandomTimeoutOnBonuses" gameID="'+gameID+'" /> <label>'+bkP.getMsg('UseSmallDelayBetweenBonuses')+'</label><br />';
	}
	
	if(e.customSource === undefined || e.customSource === true)
		e.customSource = false;
	
	var FLoptions = '';
	
	for(var i=0; i< bkP.options.friendlists.length;i++)
	{
		var v = bkP.options.friendlists[i];
		var addClass = '';
		
		if(e.customSource !== false)
		{
			if(e.customSource == 'fl_'+v.id)
				addClass = ' selected="selected"';
		}
		
		var name = v.name;
		
		if(typeof name == 'undefined')
			continue;
		
		if(name.length > 40)
		{
			name = name.slice(0, 40)+'...';
		}
		
		FLoptions += '<option value="fl_'+v.id+'"'+addClass+'>'+name+'</option>';
	}
	
	var el = $('<div gameName="'+d.name+'" class="optionsGameDiv'+(!e.enabled ? ' hide':'')+'"><img style="float: left" src="icons/menu/48'+d.systemName+'.png" /><span style="float: left;">'
	+ '<input type="checkbox" '+(e.enabled ? 'checked="checked"':'')+' class="gameEnabledBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('Enable')+' <strong>'+d.name+'</strong></label><br />'
	+ '<input type="checkbox" '+(gameID == bkP.options.defaultGame ? 'checked="checked"':'')+' class="gameDefaultBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('ShowThisGameBonusesOnFGSStart')+'</label><br />'
	+ '<input type="checkbox" '+(e.likeBonus ? 'checked="checked"':'')+' class="gameLikeBonusBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('AutoLikeBonuses')+'</label><br />'
	+ '<input type="checkbox" '+(e.likeItemsRequiringAction ? 'checked="checked"':'')+' class="gameLikeManualBonusBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('AutoLikeItemsRequiringActionWhenClicked')+'</label><br />'
	+(d.hasSendback ? '<input type="checkbox" '+(e.sendbackGift ? 'checked="checked"':'')+' class="gameSendbackGiftBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('AutoSendThankYouGift')+'</label><br />' :
	'<input type="checkbox" class="gameSendbackNotGiftBox" disabled="disable" gameID="'+gameID+'" /> <label>'+bkP.getMsg('SendThankYouGiftNotPossible')+'</label><br />')
	+ '<input type="checkbox" '+(e.hideFromFeed ? 'checked="checked"':'')+' class="gameHideFromFeedBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('HideSuccessfulBonusFromFBFeed')+'</label><br />'
	+ '<input type="checkbox" '+(e.hideFromFeedLimitError ? 'checked="checked"':'')+' class="gameHideFromFeedLimitErrorBox" gameID="'+gameID+'" /> <label>'+bkP.getMsg('HideLimitErrorBonusFromFBFeed')+'</label><br />'
	+ '<input type="checkbox" '+(e.listOnSearch? 'checked="checked"':'')+'  class="gameListOnNeighborsSearch" gameID="'+gameID+'" /> <label>'+bkP.getMsg('ListMeOnNeighborsSearch')+'</label><br />'
	+ addSpecOpt
	+ '<input type="checkbox" '+(e.customSource ? 'checked="checked"':'')+'  class="gameCustomBonusSource" gameID="'+gameID+'" /> <label>Use custom URL source for bonuses</label><br />'
	+ '<div class="friendlistsBox" style="height: 22px; line-height: 19px;"><div class="' + (e.customSource != false ? '' : 'hide') +  '"><select class="gameCustomBonusSourceSelectFriendlist" gameID="'+gameID+'">'+FLoptions+'</select></div></div>');
	
	var el2 = $('<div gameName="'+d.name+'" class="optionsGameDiv width180'+(e.enabled ? ' hide':'')+'"><img style="float: left;width:32px;height:32px;" src="icons/menu/48'+d.systemName+'.png" /><span style="margin-left: 10px;">'
	+ '<input type="checkbox" '+(e.enabled ? 'checked="checked"':'')+' class="gameEnabledBox" style="float: left;" gameID="'+gameID+'" /> <label style="float: right; width: 125px;">'+bkP.getMsg('Enable')+' <strong>'+d.name+'</strong></label></div>');

	var gs  = $('#gameOptionsTab').children('div:first');
	var gs2 = $('#gameOptionsTab').children('div:last');
	
	if(gs.children('div').length == 0)
	{
		gs.append(el);
		gs2.append(el2);
	}
	else
	{
		var added = false;
		gs.children('div').each(function(k,v)
		{
			if($(this).attr('gameName') > d.name)
			{
				$(this).before(el);
				gs2.children('div:nth-child('+(k+1)+')').before(el2);
				added = true;
				return false;
			}
		});
		if(!added)
		{
			gs.append(el);	
			gs2.append(el2);			
		}
	}
}

function addIconToGameSelector(gameID)
{
	var d =  bkP.gamesData[gameID];
	var e =  bkP.options.games[gameID];

	var el = $('<input type="radio" class="gameSelectorInput" name="gameSelectorInput" gameID="'+gameID+'" id="'+d.systemName+'Selected" /><label gameName="'+d.name+'" for="'+d.systemName+'Selected"><div class="badgeDiv hide"><span></span></div><img nosrc="icons/menu/48'+d.systemName+'.png" alt="'+d.name+'" /></label>');

	if(!e.enabled)
		el.addClass('hide');
	else
	{
		el.find('img').attr('src', el.find('img').attr('nosrc'));
		addGameMenu(gameID);
	}

	var gs = $('#gameSelector');	
	
	if(gs.children('label').length == 0)
	{
		gs.append(el);
	}
	else
	{
		var added = false;
		gs.children('label').each(function(){
			if($(this).attr('gameName') > d.name)
			{
				$(this).prev('input').before(el);
				added = true;
				return false;
			}
		});
		if(!added)
			gs.append(el);
	}
}


function addGameMenu(gameID)
{
	var game = bkP.gamesData[gameID].systemName;
	
		
	var el = $('<div id="'+game+'Game" gameID="'+gameID+'" class="gameContent hide"><ul></ul></div>');
	var elOpt = el.children('ul');
	
	$(bkP.gamesData[gameID].buttons).each(function(k,id)
	{
		var butName = bkP.submenuButtons[id].name;
		
		elOpt.append('<li><a href="#'+game+id+'" gameID="'+gameID+'">'+butName+'</a></li>');
		el.append('<div id="'+game+id+'"><div class="submenu center"><div class="submenuInfo"></div></div><div id="'+game+id+'List"><br style="clear:both" /></div></div>');
		
		var curEl = $('#'+game+id, el);
		
		if(id == 'BonusesPending' || id == 'ManualBonuses' || id == 'RequestsPending')
		{
			if(id == 'BonusesPending')
				if(bkP.gamesData[gameID].bonusNotice != undefined)
					curEl.prepend('<div style="font-size: 1.5em; font-weight:bolder;text-align: center;color: red;padding: 5px; border: 1px dotted red;margin-bottom: 10px;">'+bkP.gamesData[gameID].bonusNotice+'</div>');

			var addSearch = '<h3>'+bkP.getMsg('SimpleFilter')+'</h3> <input type="text" class="filterBonusText" /> <select class="searchWhat"><option value="1">'+bkP.getMsg('OnlyTitles')+'</option><option value="2">'+bkP.getMsg('OnlyDescriptions')+'</option><option value="0" selected="selected">'+bkP.getMsg('Both')+'</option>';
		
			curEl.find('.submenu').css('margin', '0 300px').append('<div style="float: left;position: absolute; left: 15px; width: 290px;" class="showAllButtonDiv"><span class="showAllText"></span><input type="checkbox" id="'+game+'ShowAll'+id+'" gameID="'+gameID+'" class="ShowAllItems" /><label for="'+game+'ShowAll'+id+'">'+bkP.getMsg('ShowAllItems')+'</label> <input type="checkbox" id="'+game+'ShowDescriptions'+id+'" gameID="'+gameID+'" class="ShowDescriptions" '+ ( bkP.options.showDescriptionsOnStartup == 1 ? ' checked="checked"' : '')+' /><label for="'+game+'ShowDescriptions'+id+'">'+bkP.getMsg('ShowDescriptions')+'</label><br />'+addSearch+'<br /></div>');
		}
		
		if(id == 'NeighborsSearch')
		{
			//curEl.find('#'+game+id+'List').html('<h2 class="center">'+bkP.getMsg('ClickAboveToStartSearchingForNeighbors')+'</h2>');
			curEl.html('<h2 style="text-align:center">Searching for neighbors is disabled for a few weeks</h2>');
		}
		
		if(id == 'SendFreeGifts')
		{
			curEl.find('#'+game+id+'List').html('<h2 class="center">'+bkP.getMsg('ClickAboveToLoadYourNeighborsList')+'</h2>');
		}
		
		for(var id2 in bkP.submenuButtons[id].submenu)
		{
			var sub = bkP.submenuButtons[id].submenu[id2];
			if(id == 'SendFreeGifts')
			{
				var disabled = (id2 == 'LoadNeighborsList' ? '' : ' hide ');
			}
			else
				var disabled = '';
			
			curEl.find('.submenu').append('<button class="submenuButton'+disabled+'" id="'+game+id2+'" gameID="'+gameID+'" sysID="'+id2+'">'+sub.name+'</button>');
		}
		curEl.find('.submenu').children('button').button();
	});
	
	el.insertBefore('#chat');
	el.tabs({
		show: function(event, ui)
		{
			updateTimeAgo(ui.panel.id);
			if(ui.tab.hash.match(/gameOptionsTab$/gi))
				return processLoadFiltersForGame($(ui.tab).attr('gameID'), ui.panel.id);
			
			processSwitchItemsDisplay();
		}
	});
}

function checkIconsCountInGameSelector(dontSwitchGame)
{
	if($('#gameSelector').find('label:visible').length == 3)
	{
		processGameSelectorInput($('#gameSelector').find('input:visible:last').attr('checked', 'checked'));
		$('#gameSelector').prepend('<h2>'+bkP.getMsg('NoGamesSelectedPleaseSelectSomeBelow')+'<br /><br /></h2>');
		$("#gameSelector").buttonset('refresh');
	}
	else
	{
		if(bkP.options.defaultGame != 0 && !dontSwitchGame)
		{
			var el = $('#gameSelector').children('input[gameID="'+bkP.options.defaultGame+'"]');
			if(!el.hasClass('hide'))
			{
				processGameSelectorInput(el.attr('checked', 'checked'));
				$("#gameSelector").buttonset('refresh');
			}
		}
		$('#gameSelector').children('h2').remove();
	}
}

function processGameSelectorInput(el)
{
	$('.gameContent:visible').addClass('hide');
	
	$('#currentTabName').html(' - ' + $(el).next().attr('gameName'));
	
	clearInterval(chatInterval);
	chatInterval = null;
	
	if($(el).attr('id') == 'chatSelected')
	{
		$('#chat').removeClass('hide');
		$('.shouts', '#chat').html('');
		
		$('.shoutbox').html("<h1 style='text-align:center'>Chat is disabled for a few weeks</h1>");
		return;
	}
	else if($(el).attr('id') == 'contactSelected')
	{
		$('#contact').removeClass('hide');
	}
		else if($(el).attr('id') == 'optionsSelected')
	{
		$('#options').removeClass('hide');
	}
	else
	{
		var d =  bkP.gamesData[$(el).attr('gameID')];		
		
		var tab = $('#'+d.systemName+'Game').removeClass('hide');
		
		processSwitchItemsDisplay();
		updateTimeAgo(tab.children('div').not('.hide').attr('id'));
		return;
	}
}

function processGameEnabledInput(el)
{
	var gameID = $(el).attr('gameID');
	var chk = $(el).is(':checked');

	var ico = $('#gameSelector').find('input[gameID="'+gameID+'"]').next('label').find('img');

	$('#gameOptionsTab').find('input.gameEnabledBox[gameID="'+gameID+'"]').attr('checked', chk);
	
	
	
	if(chk)
	{
		el.closest('.optionsGameDiv').hide();
		$('#gameOptionsTab').find('input[gameID="'+gameID+'"]:first').closest('.optionsGameDiv').show();
		
		
		//el.siblings().removeAttr('disabled');
		ico.closest('label').removeClass('hide');
		ico.attr('src', ico.attr('nosrc'));
		addGameMenu(gameID);
	}
	else
	{
		el.closest('.optionsGameDiv').hide();
		$('#gameOptionsTab').find('input[gameID="'+gameID+'"]:last').closest('.optionsGameDiv').show();
		//el.siblings().attr('disabled', 'disabled');
		var d =  bkP.gamesData[$(el).attr('gameID')];
		$('#'+d.systemName+'Game').remove();
		ico.closest('label').addClass('hide');
	}
	checkIconsCountInGameSelector(true);
	
	bkP.options.games[gameID].enabled = chk;
	switchEnabled(gameID, true);
	bkP.saveOptions();
	bkP.restartRequests();
}

function processGameDefaultInput(el)
{
	var gameID = $(el).attr('gameID');
	
	if($(el).is(':checked'))
	{
		bkP.options.defaultGame = gameID;
		$(".gameDefaultBox").not(el).removeAttr('checked');
	}
	else
	{
		bkP.options.defaultGame = 0;
	}
	bkP.saveOptions();
}

function processGameLikeBonusInput(el)
{
	bkP.options.games[$(el).attr('gameID')].likeBonus = $(el).is(':checked') ? true : false;
	bkP.saveOptions();
}

function processGameLikeManualBonusInput(el)
{
	bkP.options.games[$(el).attr('gameID')].likeItemsRequiringAction = $(el).is(':checked') ? true : false;
	bkP.saveOptions();
}

function processGameSendbackGiftInput(el)
{
	bkP.options.games[$(el).attr('gameID')].sendbackGift = $(el).is(':checked') ? true : false;
	bkP.saveOptions();
}

function processGameHideFromFeedInput(el)
{
	bkP.options.games[$(el).attr('gameID')].hideFromFeed = $(el).is(':checked') ? true : false;
	bkP.saveOptions();
}

function processGameHideFromFeedLimitErrorInput(el)
{
	bkP.options.games[$(el).attr('gameID')].hideFromFeedLimitError = $(el).is(':checked') ? true : false;
	bkP.saveOptions();
}

function processGameUseRandomTimeoutOnBonuses(el)
{
	bkP.options.games[$(el).attr('gameID')].useRandomTimeoutOnBonuses = $(el).is(':checked') ? true : false;
	bkP.saveOptions();
}

function processGameCustomBonusSource(el)
{
	var parent = $(el).siblings('.friendlistsBox');
	
	if(!$(el).is(':checked'))
	{
		parent.children().hide();
		bkP.options.games[$(el).attr('gameID')].customSource = false;
		bkP.saveOptions();
		
		bkP.restartBonuses();
	}
	else
	{
		parent.children().show();
		parent.find('select').trigger('change');
	}	
}

function processGameCustomBonusSourceSelectFriendlist(el)
{
	var selected = el.find('option:selected').val();
	
	bkP.options.games[$(el).attr('gameID')].customSource = selected;
	bkP.saveOptions();
	
	bkP.restartBonuses($(el).attr('gameID'));
}

function processGameListOnNeighborsSearch(el)
{
}

function emptyCallback() {}

function switchEnabled(gameID, reload)
{
	var game = bkP.gamesData[gameID].systemName;
	var enabled  = bkP.options.games[gameID].enabled;

	if(enabled == false)
	{
		if(typeof reload != 'undefined')
		{
			$('#dialog-confirm').dialog({
				open: function()
				{
					$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
					$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
					$(this).text(bkP.getMsg('ClearThisGameSettings')+' ('+bkP.gamesData[gameID].name+')');
				},
				buttons:
				{
					Clear: function()
					{
						bkP.database.clearByGameID(gameID);
						bkP.options.games[gameID] = $.extend(true,{},bkP.defaultGameOptions);						
						
						$( this ).dialog( "close" );
					},
					Cancel: function() {
						$( this ).dialog( "close" );
					}
				},
				beforeClose: function()
				{
					$(this).text(bkP.getMsg('AreYouSure'));
					delete bkP.bonusLoadingProgress[gameID];
					updateCount();
					bkP.stopBonusesForGame(gameID);		
					
				}				
			}).dialog( "open" );
		}
	}
	else
	{
		if(typeof(reload) != 'undefined')
		{
			loadBonuses(gameID);
			bkP.startBonusesForGame(gameID);
		}
	}
}

function loadComments()
{
	var el = $('#defaultCommentsMessages');
	el.html('');
	
	if(bkP.options.defaultCommentsMessages.length == 0)
	{
		el.html(bkP.getMsg('NoCommentsAddedPleaseAddSomeBelow'));
	}
	else
	{
		$(bkP.options.defaultCommentsMessages).each(function(i,msg)
		{
			el.append('<div style="float: left; width: 250px;margin-right: 10px;"><img src="icons/delete-16.png" delIndex="'+i+'" style="cursor: pointer;width: 10px;height: 10px" class="deleteComment" title="'+bkP.getMsg('DeleteComment')+'"> '+msg+'</div>');
		});	
	}

	el.append('<br style="clear:both" /><textarea style="margin-top: 50px;" class="newCommentText"></textarea><button id="saveNewComment">'+bkP.getMsg('SaveComment')+'</button>');
}

function processSaveNewComment(el)
{
	var txt = el.prev('textarea').val();
	if(txt != '')
	{
		var msg = txt;
		bkP.options.defaultCommentsMessages.push(msg);
		bkP.saveOptions();
		loadComments();
	}
}

function processDeleteComment(el)
{
	bkP.options.defaultCommentsMessages.splice($(el).attr('delIndex'),1);
	bkP.saveOptions();
	
	$(el).parent().remove();
	loadComments();
}

function processSubmenuClick(el)
{
	try
	{
		window[$(el).attr('sysID')]($(el).attr('gameID'));

	}
	catch(e)
	{
		//console.log(e);
	}
}

function processLoadFiltersForGame(gameID, opt)
{
	var arr = bkP.options.games[gameID].filter;
	arr.sort();
	
	var game = bkP.gamesData[gameID].systemName;
	
	if(arr.length == 0)
	{
		$('div#'+opt+'List').html('<h4>'+bkP.getMsg('NoFiltersAdded')+'</h4><br style="clear:both" />');
	}
	else
	{
		var html = '';
		
		for(var i = 0; i < arr.length; i++)
		{
			var v = arr[i];
			
			if(typeof v == 'string')
			{
				var title = v;
				v = {};
				
				v.title = title;
				v.image = 'icons/noimage.png';
			}
				html += '<div style="float: left; width: 250px;margin-right: 10px; height: 64px; border: 1px dotted #000;"><img src="icons/delete-48.png" delIndex="'+i+'" gameID="'+gameID+'" style="margin: 16px 8px 16px 7px; cursor: pointer;height: 32px; width: 32px;border: 1px solid #000; float: left;" class="deleteFilter" title="'+bkP.getMsg('DeleteFilter')+'"> <img style="float: left; margin: 8px 4px 8px 4px; height: 48px; width: 48px;" src="'+v.image+'" /><span style="float: right;width: 140px;font-weight:bold;margin-top:4px;">'+v.title+'</span></div>';
		}
		
		html+= '<br style="clear:both" />';
		$('div#'+opt+'List').html(html);
	}
}

function processDeleteFilter(el)
{
	var gameID = $(el).attr('gameID');
	var game = bkP.gamesData[gameID].systemName;
	
	bkP.options.games[gameID].filter.splice($(el).attr('delIndex'),1);
	bkP.saveOptions();
	
	$(el).parent().remove();
	processLoadFiltersForGame(gameID, game+'GameOptionsTab');
}

function processSwitchItemsDisplay()
{
	var gc = $('.gameContent:visible');
	
	if(gc == undefined)
		return;
	
	var gameID = gc.attr('gameID');

	var target = gc.children('div:visible').attr('id');
	
	if(target == undefined)
		return;
	
	if(!target.match(/(BonusesPending|ManualBonuses|RequestsPending)$/gi))
		return;	
	
	var game = bkP.gamesData[gameID].systemName;
	var el = $('#'+target+'List');
	var total = el.children('div').length;
	var elSub  = el.prev('.submenu');
	
	if(elSub.height() < 85)
	{
		elSub.height(85);
	}

	var showDesc = $('input.ShowDescriptions', elSub).button().is(':checked');
	var textFilter = $('input.filterBonusText', elSub).val();
	var filterType = parseInt($('select.searchWhat option:selected', elSub).val());
	el.children('div').addClass('hide');
	
	
	if(textFilter == '' || textFilter == ' ')
	{
		var matchingItems = el.children('div');
	}
	else
	{
		var found = 0;
		
		var matchingItems = el.children('div').filter(function()
		{
			var tstTitle = $('.title:Contains("'+textFilter+'")', this).length > 0 ? true : false;
			var tstDesc  = $('.description:Contains("'+textFilter+'")', this).length > 0 ? true : false;
			
			
			switch(filterType)
			{
				case 0:
					if(tstTitle || tstDesc)
					{
						found++;
						return true;
					}
					return false;
				break;
				
				case 1:
					if(tstTitle)
					{
						found++;
						return true;
					}
					return false;
				break;
				
				case 2:
					if(tstDesc)
					{
						found++;
						return true;
					}
					return false;
				break;
			}
			return false;
		});
	}
	
	if($('input.ShowAllItems', elSub).button().is(':checked'))
	{
		$('input.ShowAllItems', elSub).prev('span').html('<h3>'+bkP.getMsg('ShowingAllItems')+'</h3>');
		matchingItems.removeClass('hide');		
		appendSrcToImages(el.attr('id'));
		switchDescriptions(el.attr('id'), showDesc);
		return;
	}
	
	if(total > 100 && total == matchingItems.length)
	{
		$('input.ShowAllItems', elSub).prev('span').html('<h3>'+bkP.getMsg('Showing100ItemsTotalX', [total])+'</h3>');
		$('input.ShowAllItems', elSub).next().removeClass('hide');
	}
	else if(total > 100 && total != matchingItems.length)
	{
		$('input.ShowAllItems', elSub).prev('span').html('<h3>'+bkP.getMsg('ShowingXItemsFilteredX', [matchingItems.length, (total-matchingItems.length)])+'</h3>');
		$('input.ShowAllItems', elSub).next().removeClass('hide');
	}
	else
	{
		$('input.ShowAllItems', elSub).prev('span').html('<h3>'+bkP.getMsg('ShowingAllItems')+'</h3>');
		$('input.ShowAllItems', elSub).next().addClass('hide');
	}
	matchingItems.slice(0, 99).removeClass('hide');

	appendSrcToImages(el.attr('id'));
	switchDescriptions(el.attr('id'), showDesc);
	
	el.removeClass('hide');
}


function switchDescriptions(id, test)
{
	if(test)
	{
		$('#'+id).children('div').not('.hide').not('.withDesc').addClass('withDesc').find('.description').removeClass('hide');
	}
	else
	{
		$('#'+id).children('div.withDesc').not('.hide').removeClass('withDesc').find('.description').addClass('hide');
	}
}

function appendSrcToImages(id)
{
	$('#'+id).children('div').not('.hide').each(function(k,v)
	{
		var img = $(this).find('img[nosrc]');
		if(img.length > 0)
		{
			img.attr('src', img.attr('nosrc')).removeAttr('nosrc');
		}
	});
}
	
function windowFocus()
{
	bkP.newElements = 0;
	bkP.updateIcon();
	bkP.giftlistFocus = true;
}

function windowBlur()
{
	bkP.giftlistFocus = false;
}

function updateTimeAgo(target)
{
	var olderThanTime = bkP.options.deleteHistoryOlderThan;
	var olderBonusThanTime = bkP.options.deleteOlderThan;
	
	$('.updateTimeAgo', '#'+target).each(function()
	{
		var time = $(this).attr('time');
		var timeAgo = format_time_ago(time)
		$(this).find('.timeAgo').html(timeAgo);
	
		if($(this).hasClass('inProgress'))
		{
			return;
		}
		
		if($(this).hasClass('bonusItem') || $(this).hasClass('manualBonus'))
		{
			if($(this).hasClass('disabled'))
			{
				if(olderThanTime == 0)
				{
					return;
				}
				
				if(compareTime($(this).attr('time'), olderThanTime))
				{
					$(this).remove();
				}
			}
			else
			{
				if(olderBonusThanTime == 0)
				{
					return;
				}
				
				if(compareTime($(this).attr('time'), olderBonusThanTime))
				{
					var gameIDtmp = $(this).attr('gameID');
					$(this).remove();
					updateCount(gameIDtmp);
				}
			}
		}
		else if($(this).hasClass('requestItem'))
		{
			if($(this).hasClass('disabled'))
			{
				if(olderThanTime == 0)
				{
					return;
				}
				
				if(compareTime($(this).attr('time'), olderThanTime))
				{
					$(this).remove();
				}
			}
		}
		else if($(this).hasClass('freegiftHistory'))
		{
			if(olderThanTime == 0)
			{
				return;
			}
			
			if(compareTime($(this).attr('time'), olderThanTime))
			{
				$(this).remove();
			}
		}
	});
}

function onMouseDownTest(e)
{
	var el = $(e.srcElement || e.target);

	if(e.which == 2)
	{
		if(el.closest('div').hasClass('processBonusClick') && el.closest('div').hasClass('hasContextMenu')  && !el.closest('div').hasClass('inProgress'))
		{
			bkP.openURI(el.closest('div').attr('url'), true);
			processSingleBonusRemove(el.closest('div'));
			
		}
		e = e ? e : window.event;
		if(e.stopPropagation)
			e.stopPropagation();
		if(e.preventDefault)
			e.preventDefault();
		e.cancelBubble = true;
		e.cancel = true;
		e.returnValue = false;
		return false;
	}
}

	$(function()
	{
		$('[dataLang]').each(function()
		{
			var l = $(this).attr('dataLang');
			var d = l.split(',');
			
			if(d.length > 0)
			{
				if(d[0] == 'OlderThan')
				{
					var arr = [bkP.getMsg(d[2], [d[1]])];
					$(this).html(bkP.getMsg(d[0], arr));
				}
				else
				{
					var arr = d.slice(0, d.length-1);				
					$(this).html(bkP.getMsg(d[d.length-1], arr));
				}
			}
			else
				$(this).html(bkP.getMsg(d[0]));
		});
		
		startup();
		
		$( "#dialog-loading" ).dialog({
			resizable: false,
			width: 400,
			height: 350,
			modal: true,
			position: [Math.floor(($(this).width()-400)/2),200],
			autoOpen: true
		});
		
		$( "#progressbar" ).progressbar({
			value: 0
		});
		
		loadBonuses();
		
		$(window).click(function(e)
		{
			var el = $(e.srcElement || e.target);
			
			/*
			if(e.which == 2)
			{
				if(el.closest('div').hasClass('processBonusClick') && el.closest('div').hasClass('hasContextMenu'))
				{
					bkP.openURI(el.closest('div').attr('url'), true);
					processSingleBonusRemove(el.closest('div'));
					
				}
				return true;
			}
			*/
			
			if(e.which != 1) return true;
			
			if(el.hasClass('gameSelectorInput'))
				return processGameSelectorInput(el);
			else if(el.hasClass('gameEnabledBox'))
				return processGameEnabledInput(el);
			else if(el.hasClass('gameDefaultBox'))
				return processGameDefaultInput(el);
			else if(el.hasClass('gameLikeBonusBox'))
				return processGameLikeBonusInput(el);
			else if(el.hasClass('gameLikeManualBonusBox'))
				return processGameLikeManualBonusInput(el);
			else if(el.hasClass('gameSendbackGiftBox'))
				return processGameSendbackGiftInput(el);
			else if(el.hasClass('gameHideFromFeedBox'))
				return processGameHideFromFeedInput(el);
			else if(el.hasClass('gameHideFromFeedLimitErrorBox'))
				return processGameHideFromFeedLimitErrorInput(el);
			else if(el.hasClass('gameListOnNeighborsSearch'))
				return processGameListOnNeighborsSearch(el);
			else if(el.hasClass('gameCustomBonusSource'))
				return processGameCustomBonusSource(el);
			else if(el.hasClass('gameUseRandomTimeoutOnBonuses'))
				return processGameUseRandomTimeoutOnBonuses(el);
			else if(el.hasClass('deleteComment'))
				return processDeleteComment(el);
			else if(el.hasClass('toggleFavourite'))
				return processToggleFavourite(el);
			else if(el.hasClass('selectNeighborToSend'))
				return processSelectNeighborToSend(el);
			else if(el.hasClass('submenuButton'))
				return processSubmenuClick(el);
			else if(el.parent().hasClass('submenuButton'))
				return processSubmenuClick(el.parent());
			else if(el.hasClass('deleteFilter'))
				return processDeleteFilter(el);
			else if(el.hasClass('ShowAllItems') || el.hasClass('ShowDescriptions'))
				return processSwitchItemsDisplay();
			
			else if(el.hasClass('deleteIcon'))
				return processSingleBonusRemove(el.closest('div'));
			
			else if(el.closest('div').hasClass('processManualRequestClick'))
				return processManualRequestClick(el.closest('div'));
				
			else if(el.closest('div').hasClass('processManualBonusClick'))
				return processManualBonusClick(el.closest('div'));
			
			else if(el.closest('div').hasClass('processBonusClick'))
				return processBonusClick(el.closest('div'));
			else if(el.closest('div').hasClass('processRequestClick'))
				return processRequestClick(el.closest('div'));
			
			else if(el.hasClass('likeBonus'))
				return processLikeBonus(el);
			else if(el.hasClass('sendBack'))
				return processSendBack(el);
			else if(el.hasClass('commentBonus'))
				return processCommentBonus(el);
				
			else if(el.hasClass('friendsPageLink'))
				return friendsPaginate(el);
				
			if(el.attr('id') == 'saveNewComment')
				return processSaveNewComment(el);
		})
			.focus(windowFocus)
			.blur(windowBlur)
			.unload(windowBlur);
		
		windowFocus();

		$('#options').tabs({show: function(event, ui) { if(ui.index == 1) loadComments(); }});

		setTimeout(readNotices, 1);
		setInterval(readNotices, 300000);
		
		$('#checkBonusesTimeout > option[value="'+bkP.options.checkBonusesTimeout+'"]').attr('selected', 'selected');
		$('#checkBonusesTimeout').change(function()
		{
			bkP.options.checkBonusesTimeout = $('option:selected', this).val();
			bkP.restartBonuses();
			bkP.saveOptions();
		});
		
		$('#checkChatTimeout > option[value="'+bkP.options.checkChatTimeout+'"]').attr('selected', 'selected');
		$('#checkChatTimeout').change(function()
		{
			bkP.options.checkChatTimeout = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('#thankYouGiftMessage').val(bkP.options.thankYouGiftMessage);
		
		$('#saveThankYouGiftMessage').click(function(){
		
			bkP.options.thankYouGiftMessage = $('#thankYouGiftMessage').val();
		});
		
		$('#breakStartupLoadingOption > option[value="'+bkP.options.breakStartupLoadingOption+'"]').attr('selected', 'selected');
		$('#breakStartupLoadingCount > option[value="'+bkP.options.breakStartupLoadingCount+'"]').attr('selected', 'selected');
		$('#breakStartupLoadingTime > option[value="'+bkP.options.breakStartupLoadingTime+'"]').attr('selected', 'selected');
		
		if(bkP.options.breakStartupLoadingOption == 0)
			$('#breakStartupLoadingCount').css('display', 'block');
		else
			$('#breakStartupLoadingTime').css('display', 'block');

		$('#breakStartupLoadingCount').change(function()
		{
			bkP.options.breakStartupLoadingCount = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('#breakStartupLoadingTime').change(function()
		{
			bkP.options.breakStartupLoadingTime = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('#breakStartupLoadingOption').change(function()
		{
			bkP.options.breakStartupLoadingOption = $('option:selected', this).val();
			
			if($('option:selected', this).val() == 0)
			{
				$('#breakStartupLoadingTime').css('display', 'none');
				$('#breakStartupLoadingCount').css('display', 'block');
			}
			else
			{
				$('#breakStartupLoadingCount').css('display', 'none');
				$('#breakStartupLoadingTime').css('display', 'block');
			}
			bkP.saveOptions();
		});
		
		$('.gameCustomBonusSourceSelectFriendlist').live('change', function(e)
		{
			var el = $(e.srcElement || e.target);
			
			return processGameCustomBonusSourceSelectFriendlist(el);
		});
		
		for(var l in bkP.transObj)
		{
			$('#selectFGSLanguage').append('<option value="'+l+'">'+bkP.transObj[l].name+'</option>');
		}
		
		$('#selectFGSLanguage > option[value="'+bkP.options.language+'"]').attr('selected', 'selected');
		$('#selectFGSLanguage').change(function()
		{
			bkP.options.language = $('option:selected', this).val();
			bkP.loadSubmenu();
			bkP.saveOptions();
			alert(bkP.getMsg('LanguageChanged'));			
			bkP.sendView('close');			
		});
		
		$('#deleteOlderThan > option[value="'+bkP.options.deleteOlderThan+'"]').attr('selected', 'selected');
		$('#deleteOlderThan').change(function()
		{
			bkP.options.deleteOlderThan = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('#deleteHistoryOlderThan > option[value="'+bkP.options.deleteHistoryOlderThan+'"]').attr('selected', 'selected');
		$('#deleteHistoryOlderThan').change(function()
		{
			bkP.options.deleteHistoryOlderThan = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('#collectXbonusesAtTheSameTime > option[value="'+bkP.options.collectXbonusesAtTheSameTime+'"]').attr('selected', 'selected');
		$('#collectXbonusesAtTheSameTime').change(function()
		{
			bkP.options.collectXbonusesAtTheSameTime = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('#showDescriptionsOnStartup > option[value="'+bkP.options.showDescriptionsOnStartup+'"]').attr('selected', 'selected');
		$('#showDescriptionsOnStartup').change(function()
		{
			bkP.options.showDescriptionsOnStartup = $('option:selected', this).val();
			bkP.saveOptions();
		});
		
		$('.filterBonusText').data('timeout', null).live('keyup', function()
		{
            clearTimeout(jQuery(this).data('timeout'));
            jQuery(this).data('timeout', setTimeout(processSwitchItemsDisplay, 500));
        });		
		
		
		$(".showContext").live('mouseenter', function()
		{
			if($(this).hasClass('hasContextMenu'))
			{
				return;
			}
			$(this).addClass('hasContextMenu').contextMenu({
				menu: 'myMenu'
			}, function(action, el, pos) {
				
				if(action == 'receive')
				{
					processBonusClick(el);
				}
				else if(action == 'receiveSimilar')
				{
					el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function(){
						processBonusClick($(this));
					});
				}
				else if(action == 'delete')
				{
					processSingleBonusRemove(el);
				}
				else if(action == 'deleteSimilar')
				{
					$('#dialog-confirm').dialog({
						open: function()
						{
							$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
							$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
						},
						buttons:
						{
							Clear: function()
							{
								el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function()
								{
									$(this).remove();
								});
								bkP.database.deleteItemByTitle('bonuses', el.attr('gameID'), el.attr('search-title'), 0);
								updateCount(el.attr('gameID'));
								
								$( this ).dialog( "close" );
							},
							Cancel: function() {
								$( this ).dialog( "close" );
							}
					}});
					
					$('#dialog-confirm').dialog('open');
				}
				else if(action == 'stopCollect')
				{
					$('#dialog-confirm').dialog({
						open: function()
						{
							$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('StopCollecting'));
							$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
						},
						buttons:
						{
							StopCollecting: function()
							{
								var image = el.find('img:last').attr('src');
								bkP.options.games[el.attr('gameID')].filter.push({"title": el.attr('search-title'), "image": image});
								bkP.saveOptions();
								el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function()
								{
									$(this).remove();
								});
								bkP.database.deleteItemByTitle('bonuses', el.attr('gameID'), el.attr('search-title'), 0);
								updateCount(el.attr('gameID'));
								
								$( this ).dialog( "close" );
							},
							Cancel: function() {
								$( this ).dialog( "close" );
							}
					}});
					
					$('#dialog-confirm').dialog('open');
				}
				else if(action == 'copylink')
				{
					bkP.copyLink(el.attr('url'));
				}
				else if(action == 'openAndDelete')
				{
					bkP.openURI(el.attr('url'), true);
					processSingleBonusRemove(el);
				}
				else if(action == 'debug')
				{
					bkP.openURI(el.attr('url'), true);
				}
			});
		});
		
		$(".showContextRequests").live('mouseenter', function()
		{
			if($(this).hasClass('hasContextMenu'))
			{
				return;
			}
			$(this).addClass('hasContextMenu').contextMenu({
				menu: 'myMenuRequests'
			}, function(action, el, pos) {
				
				if(action == 'receive')
				{
					processRequestClick(el);
				}
				else if(action == 'receiveSimilar')
				{
					el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function(){
						processRequestClick($(this));
					});
				}
				else if(action == 'delete')
				{
					var postData = el.attr('postData');
					
					el.remove();
					bkP.database.deleteItem('requests', el.attr('gameID'), el.attr('id'), 0);
					updateCount(el.attr('gameID'));
					
					var game = bkP.gamesData[el.attr('gameID')].systemName;

					if(el.hasClass('isMessageCenterGift'))
					{
						var obj = {}
						obj.data = JSON.parse(unescape(postData));
						obj.gameID = el.attr('gameID');
						obj.deleteItem = true;
						
						bkP[game].MessageCenter.Receive(obj);
					}
					else
					{
						bkP.emptyUnwantedGifts(postData);
					}
				}
				else if(action == 'deleteSimilar')
				{
					$('#dialog-confirm').dialog({
						open: function()
						{
							$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
							$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
						},
						buttons:
						{
							Clear: function()
							{
								el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function()
								{
									var postData = $(this).attr('postData');
									
									if($(this).hasClass('isMessageCenterGift'))
									{
										var game = bkP.gamesData[el.attr('gameID')].systemName;
										
										var obj = {}
										obj.data = JSON.parse(unescape(postData));
										obj.gameID = el.attr('gameID');
										obj.deleteItem = true;
										
										bkP[game].MessageCenter.Receive(obj);
									}
									else
									{
										bkP.emptyUnwantedGifts(postData);
									}
									$(this).remove();
								});
								
								bkP.database.deleteItemByTitle('requests', el.attr('gameID'), el.attr('origTitle'), 0);
								updateCount(el.attr('gameID'));
								
								$( this ).dialog( "close" );
							},
							Cancel: function() {
								$( this ).dialog( "close" );
							}
					}});
					
					$('#dialog-confirm').dialog('open');
				}
				else if(action == 'debug')
				{
					if(el.hasClass('isMessageCenterGift'))
					{
						alert('This is a message center gift. It doesn\'t support debug');
					}
					else
						bkP.prepareLinkForGame('', el.attr('id'), el.attr('postData'), true);
					//el.remove();
				}
			});
		});
		
		
		$(".showContextManual").live('mouseenter', function()
		{
			if($(this).hasClass('hasContextMenu'))
			{
				return;
			}
			$(this).addClass('hasContextMenu').contextMenu({
				menu: 'myMenuManualBonuses'
			}, function(action, el, pos)
			{
				if(action == 'delete')
				{
					el.remove();
					bkP.database.deleteItem('bonuses', el.attr('gameID'), el.attr('id'), 0);
					updateCount(el.attr('gameID'));
				}
				else if(action == 'deleteSimilar')
				{
					$('#dialog-confirm').dialog({
						open: function()
						{
							$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('ClearEverything'));
							$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
						},
						buttons:
						{
							Clear: function()
							{
								el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function()
								{
									$(this).remove();
								});
								bkP.database.deleteItemByTitle('bonuses', el.attr('gameID'), el.attr('search-title'), 0);
								updateCount(el.attr('gameID'));
								$( this ).dialog( "close" );
							},
							Cancel: function() {
								$( this ).dialog( "close" );
							}
					}});
					
					$('#dialog-confirm').dialog('open');
				}
				else if(action == 'stopCollect')
				{
					$('#dialog-confirm').dialog({
						open: function()
						{
							$(this).parent().find('.ui-dialog-buttonset').find('span:first').text(bkP.getMsg('StopCollecting'));
							$(this).parent().find('.ui-dialog-buttonset').find('span:last').text(bkP.getMsg('Cancel'));
						},
						buttons:
						{
							StopCollecting: function()
							{
								var image = el.find('img:last').attr('src');
								bkP.options.games[el.attr('gameID')].filter.push({"title": el.attr('search-title'), "image": image});
								bkP.saveOptions();
								el.parent().find('div[search-title="'+el.attr('search-title')+'"]').not('.inProgress').each(function()
								{
									$(this).remove();
								});
								bkP.database.deleteItemByTitle('bonuses', el.attr('gameID'), el.attr('search-title'), 0);
								updateCount(el.attr('gameID'));
								
								$( this ).dialog( "close" );
							},
							Cancel: function() {
								$( this ).dialog( "close" );
							}
					}});
					$('#dialog-confirm').dialog('open');
				}
				else if(action == 'copylink')
				{
					bkP.copyLink(el.attr('url'));
				}
			});
		});
		
		$(".selectGiftToSend").live('mouseenter', function()
		{
			if($(this).hasClass('hasContextMenu'))
			{
				return;
			}
			$(this).addClass('hasContextMenu').contextMenu({
				menu: 'myMenuDefaultGift'
			}, function(action, el, pos)
			{
				if(action == 'selectDefault')
				{
					el.siblings(".selectGiftToSend").removeClass('selected');
					el.addClass('selected');
					
					bkP.options.games[el.attr('gameID')].defaultGift = el.attr('giftID');					
					bkP.saveOptions();
				}
			}).click(function(){
				$(this).siblings("div.selectGiftToSend").removeClass('selected');
				$(this).addClass('selected');
			});
		});

		$( "#dialog-confirm" ).dialog({
			resizable: false,
			autoOpen: false,
			height:140,
			modal: true
		});
		
		$( "#dialog-error" ).dialog({
			resizable: false,
			autoOpen: false,
			height:'auto',
			modal: true
		});
		
		$( "#dialog-normal" ).dialog({
			resizable: false,
			autoOpen: false,
			height:'auto',
			modal: true
		});
		
		
		
		
		$('#lockScreen').button().click(function()
		{
			isScreenLocked = $(this).is(':checked');
			
			if($(this).is(':checked'))
			{
				$(this).button('option', 'label', bkP.getMsg('ScreenIsLocked'));
			}
			else
			{
				$(this).button('option', 'label', bkP.getMsg('ScreenIsUnlocked'));
				updateCount();
				var procArr = screenLockedData;
				screenLockedData = [];
				
				$(procArr).each(function(k,v)
				{
					if(v.id == '')
						window[v.callback](v.data);
					else
						window[v.callback](v.id, v.data);					
				});
			}
		});
		
		
		$('#receiveBonusesAllGames').button().click(function()
		{
			for(var idd in bkP.gamesData)
			{
				if(bkP.options.games[idd].enabled)
				{
					ReceivePendingBonuses(idd);
				}
			}
		});
		
		$('#receiveGiftsAllGames').button().click(function()
		{
			for(var idd in bkP.gamesData)
			{
				if(bkP.options.games[idd].enabled)
				{
					ReceivePendingRequests(idd);
				}
			}
		});
		
		$('#removeRequiringActionAllGames').button().click(function()
		{
			ClearAllManualBonuses();
		});
		
		
		
		$('#stopReceivingQueue').button().click(function()
		{
			$(bkP.stopQueue()).each(function(k,v)
			{
				var id = v.id;
				
				if(v.type == 'bonus')
				{
					$('#'+id).enableContextMenu().removeClass('inProgress');
					$('#'+id).find('img:last').attr('src', $('#'+id).find('img:last').attr('orig-src'));
				}
				else
				{
					$('#'+id).enableContextMenu().removeClass('inProgress');
					$('#'+id).find('img:last').attr('src', $('#'+id).find('img:last').attr('orig-src'));
				}
			});
			
			updateQueueCount();
		});
		
		$('#exportSettings').click(function()
		{
			var set = jQuery.extend(true,{},bkP.options);
			var cleanSet = {};
			
			for(var id in set)
			{
				if(typeof(bkP.defaultOptions[id]) != 'undefined')
				{
					cleanSet[id] = set[id];
				}
			}	
			var set = JSON.stringify(cleanSet);

			$('#settingsTextarea').click(function(){
				$(this).focus().select();
			});
			
			$('#settingsTextarea').val(set).trigger('click');			
		});
		
		$('#importSettings').click(function()
		{
			var txt = $('#settingsTextarea').val();
			
			try
			{
				if(txt == '') throw {}
				var set = JSON.parse(txt);

				var cleanSet = {}
				
				for(var id in set)
				{
					if(typeof(bkP.defaultOptions[id]) != 'undefined')
					{
						cleanSet[id] = set[id];
					}
				}
				
				alert(bkP.getMsg('ImportSuccessful'));
				bkP.options = bkP.jQuery.extend(true,{}, bkP.defaultOptions,	cleanSet);
				bkP.FBloginError = null;
				bkP.updateIcon();
				bkP.sendView('closeAndOpen');
			}
			catch(e)
			{
				alert(bkP.getMsg('ImportError'));
			}			
		});
		
	});
	
	function updateQueueCount()
	{
		$('#queueItemsCount').text((bkP.xhrQueue.length+bkP.xhrFarmQueue.length));
	}

	function processSelectNeighborToSend(e)
	{
		var gameID = $(e).attr('gameID');
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';

		var count = parseInt($('input[name="neighArr[]"]:checked', 'div#'+game+opt).length);

		if(count > 25)
		{
			return false;
		}
	}
	
	function processSingleBonusRemove(el)
	{
		el.remove();
		bkP.database.deleteItem('bonuses', el.attr('gameID'), el.attr('id'), 0);
		updateCount(el.attr('gameID'));
	}
	
	function processToggleFavourite(e)
	{
		var srcEl	= $(e);
		var gameID 	= srcEl.attr('gameID');
		var uID		= srcEl.attr('neighID');
		var srcEl	= srcEl.closest('tr');
		
		var game = bkP.gamesData[gameID].systemName;
		var opt = 'SendFreeGiftsList';
				
		var idx = bkP.options.games[gameID].favourites.indexOf(uID);
				
		if(idx == -1)
		{
			bkP.options.games[gameID].favourites.push(uID);
			
			var arr =
				[
					'<img src="icons/favourite.png" gameID="'+gameID+'" neighID="'+uID+'" class="toggleFavourite">',
					srcEl.children('td:nth-child(2)').html(),
					srcEl.children('td:nth-child(3)').html(),
					srcEl.children('td:nth-child(4)').html(),
					srcEl.children('td:nth-child(5)').html(),
					srcEl.children('td:nth-child(6)').html(),
					srcEl.children('td:nth-child(7)').html(),
					srcEl.children('td:nth-child(8)').html(),
					srcEl.children('td:nth-child(9)').html()
				];

			$('.favouritesTable', 'div#'+game+opt).dataTable().fnAddData(arr);
			$('.neighborsTable', 'div#'+game+opt).dataTable().fnDeleteRow( srcEl[0] );
		}
		else
		{
			bkP.options.games[gameID].favourites.splice(idx, 1);
			
			var arr =
				[
					'<img src="icons/favourite-bw.png" gameID="'+gameID+'" neighID="'+uID+'" class="toggleFavourite">', 
					srcEl.children('td:nth-child(2)').html(),
					srcEl.children('td:nth-child(3)').html(),
					srcEl.children('td:nth-child(4)').html(),
					srcEl.children('td:nth-child(5)').html(),
					srcEl.children('td:nth-child(6)').html(),
					srcEl.children('td:nth-child(7)').html(),
					srcEl.children('td:nth-child(8)').html(),
					srcEl.children('td:nth-child(9)').html()
				];
			
			$('.neighborsTable', 'div#'+game+opt).dataTable().fnAddData(arr);
			$('.favouritesTable', 'div#'+game+opt).dataTable().fnDeleteRow( srcEl[0] );
		}
		bkP.saveOptions();
	}
	
	function processLikeBonus(el)
	{
		if(!el.hasClass('disabledLike'))
		{
			var bonusID = el.parent().parent().parent().parent().attr('id');
			el.addClass('disabledLike').attr('src', 'gfx/act_indicator.gif');
			bkP.likeBonus(bonusID);
		}
	}

	function processCommentBonus(el)
	{
		if(bkP.options.defaultCommentsMessages.length == 0)
		{
			alert(bkP.getMsg('SetupCommentsBeforePosting'));
		}
		else
		{
			if(!el.hasClass('disabledComment'))
			{
				var randNum = Math.floor(Math.random()*(bkP.options.defaultCommentsMessages.length));
				var bonusID = el.parent().parent().parent().parent().attr('id');
				el.addClass('disabledComment').attr('src', 'gfx/act_indicator.gif');
				bkP.commentBonus(bonusID, bkP.options.defaultCommentsMessages[randNum]);
			}
		}
	}
	
	function processSendBack(el)
	{
		if(!el.hasClass('disabledSendback'))
		{
			var bonusID = el.parent().parent().parent().parent().attr('id');
			el.addClass('disabledSendback').attr('src', 'gfx/act_indicator.gif');

			var gameID =  el.parent().parent().parent().parent().attr('gameID');
			
			var tempData = JSON.parse(el.next().text());
			
			if(typeof tempData.destInt == 'undefined' || tempData.destInt == '')
			{
				var postData = el.parent().parent().parent().parent().attr('postData');
				tempData.destInt = bkP.Gup('params\\\[from_id\\\]', postData);
			}
			
			if(tempData.destInt.toString().indexOf(',') != -1)
			{
				var sendArr = [];
				var ids = tempData.destInt.split(',');
				
				for(var i=0; i<ids.length;i++)
				{
					sendArr.push(ids[i]);
				}
			}
			else
			{
				var sendArr = [tempData.destInt];
			}
			
			
			var params = {
				gift: tempData.gift,
				gameID:	gameID,
				sendTo: sendArr,
				sendToName: tempData.destName,
				thankYou: true,
				bonusID: bonusID,	
				isRequest: el.parent().parent().parent().parent().hasClass('bonusItem') ? false : true
			};
			
			var game = bkP.gamesData[gameID].systemName;
			
			bkP[game].Freegifts.Click(params);
		}
	}
	
	function updateSendback(bonusID, success, isDailyLimit)
	{
		if(success)
		{
			$('img.sendBack', '#'+bonusID).addClass('disabledSendback').removeClass('sendBack').attr('src', 'gfx/23check.png').css('cursor', 'default').attr('title', bkP.getMsg('ThankYouGiftAlreadySent'));
		}
		else if(isDailyLimit)
		{
			$('img.sendBack', '#'+bonusID).addClass('disabledSendback').removeClass('sendBack').attr('src', 'gfx/23error.png').css('cursor', 'default').attr('title', bkP.getMsg('ThankYouGiftAlreadySentToday'));
		}
		else
		{
			$('img.sendBack', '#'+bonusID).removeClass('disabledSendback').attr('src', 'gfx/23error.png').attr('title', bkP.getMsg('ErrorWhileSendingThankYouGift'))
		}
	}
	
	function updateLike(bonusID, error)
	{
		
		var img = $('img.likeBonus', '#'+bonusID);
		
		if(img.length > 0)
		{
			updateLikeState('#'+bonusID, error);
		}
		else
		{
			if(error == 0)
			{
				$('#'+bonusID).attr('isLiked', 1);
			}
		}
	}
	
	function updateLikeState(selector, error)
	{
		if(error == 0)
		{
			$('img.likeBonus', selector).addClass('disabledLike').removeClass('likeBonus').attr('src', 'gfx/like-off.png').css('cursor', 'default').attr('title', bkP.getMsg('YouHaveAlreadyLikedThis'));
		}
		else
		{
			$('img.likeBonus', selector).removeClass('disabledLike').attr('src', 'gfx/like.png');
		}
	}
	
	function updateCommentState(selector, error)
	{
		if(error == 0)
		{
			$('img.commentBonus', selector).addClass('disabledComment').removeClass('commentBonus').attr('src', 'gfx/comment-off.png').css('cursor', 'default').attr('title', bkP.getMsg('YouHaveAlreadyPostedCommentOnThis'));
		}
		else
		{
			$('img.commentBonus', selector).removeClass('disabledComment').attr('src', 'gfx/comment.png');
		}
	}
	
	function updateComment(bonusID, error)
	{
		var img = $('img.commentBonus', '#'+bonusID);
		
		if(img.length > 0)
		{
			updateCommentState('#'+bonusID, error);
		}
		else
		{
			if(error == 0)
			{
				$('#'+bonusID).attr('isCommented', 1);
			}
		}
	}
	
	function changeSendbackState(bonusID)
	{
		var img = $('img.sendBack', '#'+bonusID);
		
		if(img.length > 0)
		{
			updateSendbackState('#'+bonusID);
		}
		else
		{
			$('#'+bonusID).attr('SendbackInProgress', 1);
		}
	}
	
	function updateSendbackState(selector)
	{
		$('img.sendBack', selector).addClass('disabledSendback').css('cursor', 'default').attr('src', 'gfx/act_indicator.gif').attr('title', bkP.getMsg('InProgress'));
	}
		
	function compareTime(itemTime, olderThan)
	{
		var now = new Date().getTime();
		var itemTime = new Date(itemTime*1000).getTime();
		
		var diff = now-itemTime;
		var secs = Math.floor(diff.valueOf()/1000);		
		return(secs > olderThan ? true : false);
	}
</script>
</head>
<body>
	<div style="float: left; width: 20%;padding-top: 10px;">
		<div id="notices" style="margin: 0 10px; padding: 5px;height: 200px;" class="ui-widget ui-tabs ui-widget-content ui-corner-all">
			<div id="noticesScript" style="display:none"></div>
			<div id="noticesContent" style="height: 200px;overflow: auto; overflow-x hidden;">
			</div>
		</div>
	</div>
	
	<div style="float: left; width: 80%;padding-top: 10px;">
		<div id="gameSelector" style="margin: 0px 0px; display: block;text-align:center;"></div>
		
		<br />
	
		<h1 class="icon" style="background-image: url(gfx/32px-icon.png); margin-left: 0 10px;">Fancy Gaming Simplifier - v. <span id="currentVersion"></span> <span id="currentTabName"></span> 
		</h1>
		<br style="clear: both" />
		
		<h2 style="text-align: center">
			<button style="font-size: 0.8em;" id="receiveBonusesAllGames" dataLang="ReceiveBonusesFromAllGames"></button>
			<input type="checkbox" id="lockScreen" /><label for="lockScreen" style="font-size: 0.9em;" dataLang="ScreenIsUnlocked"></label>
			<button style="font-size: 0.8em;" id="receiveGiftsAllGames" dataLang="ReceiveGiftsFromAllGames"></button><br /><br />
				<button style="font-size: 0.8em;" id="removeRequiringActionAllGames" dataLang="RemoveRequiringActionFromAllGames"></button>
			<br /><br />
			<button style="font-size: 0.8em;" id="stopReceivingQueue"><span dataLang="ResetItemsQueue"></span> (<span id="queueItemsCount">0</span>)</button>
		</h2>
	</div>
		<br style="clear: both" />
		<br style="clear: both" />

		<div id="chat" style="padding: 20px" class="hide gameContent  ui-widget ui-tabs ui-widget-content ui-corner-all">
				<div align="left" id="chatUsers" class="chatContent right">
					<h2 style="text-align:center;border-bottom:1px dashed #000;padding-bottom:5px;" dataLang="Chat"></h2>
					<div class="shoutbox">
						<div class="shouts"></div>
					</div>
					
					<div class="onlinelist">
						<div class="onlineText"><strong dataLang="UsersOnline"></strong></div>
						<div class="users"></div>
					</div>
					
					<div style="border-top: 1px dashed #000;padding-top: 10px;">
						<form method="post" action="javascript:void(0);" onsubmit="send(this)" id="publicChat" autocomplete="off">
							<img src="./gfx/act_indicator.gif" class="act_indicator" style="visibility: hidden; ">
							<strong dataLang="Message"></strong> <input type="text" tabindex="1" disabled="disabled" name="message" class="message" value="">
						</form>
					</div>
				</div>
				<br style="clear: both" />
		</div>
		
		<div id="options" class="hide gameContent">
			<ul>
				<li><a href="#gameOptionsTab" dataLang="GameSelector"></a></li>
				<li><a href="#optionTab-2" dataLang="Options"></a></li>
				<li><a href="#optionTab-3" dataLang="ImportExport"></a></li>
			</ul>
			<div id="gameOptionsTab">
				<h2 dataLang="EnabledGames"></h2>
				<div></div>
				
				<br style="clear: both;" />
				
				<h2 style="margin-top: 30px;" dataLang="AvailableGames"></h2>
				<div></div>			
			</div>
			<div id="optionTab-2">
				<p>
					
					<div style="float: left;width: 45%;">
						<h1 dataLang="MainOptions"></h1>
						
						<h4 dataLang="SelectFGSLanguage"></h4>
							<select id="selectFGSLanguage">
								<option value="0" dataLang="UseFacebookLanguage"></option>
							</select>
						
						
						<h4 dataLang="DeleteBonusesOlderThan"></h4>
							<select id="deleteOlderThan">
								<option value="0" dataLang="Never"></option>
								<option value="1800" dataLang="30,Minutes"></option>
								<option value="3600" dataLang="1,Hour"></option>
								<option value="7200" dataLang="2,Hours"></option>
								<option value="10800" dataLang="3,Hours"></option>
								<option value="21600" dataLang="6,Hours"></option>
								<option value="43200" dataLang="12,Hours"></option>
								<option value="86400" dataLang="1,Day"></option>
								<option value="172800" dataLang="2,Days"></option>
								<option value="259200" dataLang="3,Days"></option>		
								<option value="604800" dataLang="7,Days"></option>
								<option value="1209600" dataLang="14,Days"></option>
								<option value="2592000" dataLang="30,Days"></option>
							</select>
						
						<h4 dataLang="DeleteHistoryOlderThan"></h4>
							<select id="deleteHistoryOlderThan">
								<option value="0" dataLang="Never"></option>
								<option value="1800" dataLang="30,Minutes"></option>
								<option value="3600" dataLang="1,Hour"></option>
								<option value="7200" dataLang="2,Hours"></option>
								<option value="10800" dataLang="3,Hours"></option>
								<option value="21600" dataLang="6,Hours"></option>
								<option value="43200" dataLang="12,Hours"></option>
								<option value="86400" dataLang="1,Day"></option>
								<option value="172800" dataLang="2,Days"></option>
								<option value="259200" dataLang="3,Days"></option>		
								<option value="604800" dataLang="7,Days"></option>
								<option value="1209600" dataLang="14,Days"></option>
								<option value="2592000" dataLang="30,Days"></option>
							</select>

						<h4 dataLang="HowManyBonusesToCollectAtOnce"></h4>
							<select id="collectXbonusesAtTheSameTime">
								<option value="1">1</option>
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="4">4</option>
								<option value="5">5</option>
								<option value="10">10</option>
								<option value="15">15</option>
								<option value="25">25</option>
								<option value="30">30</option>
							</select>
						
						<h4 dataLang="ShowItemsDescriptions"></h4>
							<select id="showDescriptionsOnStartup">
								<option value="0" dataLang="No"></option>
								<option value="1" dataLang="Yes"></option>
							</select>

						<h4 dataLang="BonusesCheckTimeout"></h4>
							<select id="checkBonusesTimeout">
								<option value="15" dataLang="15,Seconds"></option>
								<option value="30" dataLang="30,Seconds"></option>
								<option value="60" dataLang="1,Minute"></option>
								<option value="120" dataLang="2,Minutes"></option>
								<option value="180" dataLang="3,Minutes"></option>
								<option value="300" dataLang="5,Minutes"></option>
							</select>
						
						<h4 dataLang="ChatRefreshTimeout"></h4>
							<select id="checkChatTimeout">
								<option value="15" dataLang="15,Seconds"></option>
								<option value="30" dataLang="30,Seconds"></option>
								<option value="60" dataLang="1,Minute"></option>
								<option value="120" dataLang="2,Minutes"></option>
							</select>
						
						<br /><br />
						
						<h4 dataLang="ThankYouGiftMessage"></h4>
						<input type="text" id="thankYouGiftMessage" />
						<button id="saveThankYouGiftMessage" dataLang="Save"></button>
						
						<br /><br />
						
						<h4 dataLang="RandomCommentMessages"></h4>
						<div id="defaultCommentsMessages"></div>
					</div>
					
					<div style="float: right;width: 45%;">
						<h1 dataLang="AdvancedOptions"></h1>
						
						<h2 style="color: red" dataLang="ReadBeforeChangingNotice"></h2>
						
						<div dataLang="AdvancedOptionsNotice"></div>
						<br /><br />
						
						<h3 dataLang="StopSearchingForFeedsWhen"></h3>
						
							<select id="breakStartupLoadingOption">
								<option value="0" dataLang="FoundCertainAmountOfFeeds"></option>
								<option value="1" dataLang="BonusesAreOlderThanSpecifiedTime"></option>
							</select>
						
							<select id="breakStartupLoadingCount" style="display: none">
								<option value="100" dataLang="100,Items"></option>
								<option value="200" dataLang="200,Items"></option>
								<option value="300" dataLang="300,Items"></option>
								<option value="500" dataLang="500,Items"></option>
								<option value="1000" dataLang="1000,Items"></option>
								<option value="1500" dataLang="1500,Items"></option>
								<option value="2500" dataLang="2500,Items"></option>
							</select>
							
							<select id="breakStartupLoadingTime" style="display: none">
								<option value="1800" dataLang="OlderThan,30,Minutes"></option>
								<option value="3600" dataLang="OlderThan,1,Hour"></option>
								<option value="7200" dataLang="OlderThan,2,Hours"></option>
								<option value="10800" dataLang="OlderThan,3,Hours"></option>
								<option value="21600" dataLang="OlderThan,6,Hours"></option>
								<option value="43200" dataLang="OlderThan,12,Hours"></option>
								<option value="86400" dataLang="OlderThan,1,Day"></option>
							</select>
					
					</div>

					<br style="clear: both" />
				</p>
			</div>
			<div id="optionTab-3">
				<p>			
					<h3 class="settings" dataLang="ImportExportSettings"></h3>
					
					<textarea cols="40" rows="5" id="settingsTextarea"></textarea><br /><br />
					
					<button id="importSettings" dataLang="Import"></button> <button id="exportSettings" dataLang="Export"></button>	<br /><br /><br />
					
					<h4 dataLang="HowToImport"></h4>
					<div dataLang="ImportInstructions"></div>
					<br /><br />
					
					<h4 dataLang="HowToExport"></h4>
					<div dataLang="ExportInstructions"></div>
				</p>
			</div>
		</div>
			
		<div id="contact" style="padding: 20px" class="hide gameContent  ui-widget ui-tabs ui-widget-content ui-corner-all">
			<h2 dataLang="ContactInfoNotice"></h2><br />
				<h2>Contact info will be provided soon</h2>			
			
		</div>
	

	<div id="dialog-confirm" title="Delete?">
		<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span><span class="text" dataLang="AreYouSure"></span></p>
	</div>
	
	<div id="dialog-error" title="Error">
		<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span><span class="text"></span></p>
	</div>
	
	<div id="dialog-loading" title="Loading Gifts and Bonuses List">
		<h3 class="center"><img src="gfx/dl.gif"><br /><span dataLang="NotLoadedYetPleaseWait"></span></h3><br /><br />
		<span dataLang="LoadingScreenLongWaitNotice"></span><br />
		<div id="progressbar"></div>
	</div>
	
	<div id="dialog-normal" title="Information window">
		
	</div>


	
	<ul id="myMenu" class="contextMenu">
		<li class="receive"><a href="#receive"dataLang="ReceiveThisItem"></a></li>
		<li class="receive"><a href="#receiveSimilar"><span dataLang="Receive"></span> "<span class="bonusName"></span> (<span class="bonusNameCount"></span>)"</a></li>
		<li class="delete separator"><a href="#delete" dataLang="ClearThisItem"></a></li>
		<li class="delete"><a href="#deleteSimilar"><span dataLang="Clear"></span> "<span class="bonusName"></span> (<span class="bonusNameCount"></span>)"</a></li>
		<li class="delete separator"><a href="#stopCollect" dataLang="StopCollecting"></span> "<span class="bonusName"></span>"</a></li>
		<li class="copy separator"><a href="#copylink" dataLang="CopyLink"></a></li>
		<li class="open separator"><a href="#openAndDelete" dataLang="OpenInNewTabAndClear"></a></li>
		<li class="debug separator"><a href="#debug" dataLang="DebugItem"></a></li>
	</ul>
	
	<ul id="myMenuManualBonuses" class="contextMenu">
		<li class="delete separator"><a href="#delete" dataLang="ClearThisItem"></a></li>
		<li class="delete"><a href="#deleteSimilar"><span dataLang="Clear"></span> "<span class="bonusName"></span> (<span class="bonusNameCount"></span>)"</a></li>
		<li class="delete separator"><a href="#stopCollect"><span dataLang="StopCollecting"></span> "<span class="bonusName"></span>"</a></li>
		<li class="copy separator"><a href="#copylink" dataLang="CopyLink"></a></li>
	</ul>
	
	<ul id="myMenuRequests" class="contextMenu">
		<li class="receive"><a href="#receive" dataLang="ReceiveThisItem"></a></li>
		<li class="receive"><a href="#receiveSimilar"><span dataLang="Receive"></span> "<span class="bonusName"></span> (<span class="bonusNameCount"></span>)"</a></li>
		<li class="delete separator"><a href="#delete" dataLang="ClearThisItem"></a></li>
		<li class="delete"><a href="#deleteSimilar"><span dataLang="Clear"></span> "<span class="bonusName"></span> (<span class="bonusNameCount"></span>)"</a></li>
		<li class="debug"><a href="#debug" dataLang="DebugItem"></a></li>
	</ul>
	
	<ul id="myMenuDefaultGift" class="contextMenu">
		<li class="receive"><a href="#selectDefault" dataLang="SelectAsDefaultGift"></a></li>
	</ul>
	
	<ul id="myMenuGameIcon" class="contextMenu">
		<li class="goToGame"><a href="#goToGame"><strong dataLang="GoToThisGame"></strong></a></li>
	</ul>
</body>
</html>